执行Python脚本的Shell运行后,终端无法自动关闭的问题
终端无法自动退出的问题解决
问题根源
你的脚本执行完毕后终端无法自动退出,是因为sc-2.py中用subprocess.Popen启动子进程后未等待其完成,且子进程与终端的IO资源未彻底切断,导致终端一直处于等待状态。
具体解决方案
方案1:等待子进程执行完成
修改sc-2.py,在启动子进程后调用wait()方法,让主进程等子进程跑完再退出:
import subprocess print('Script 2 started') proc = subprocess.Popen(["sh", "test.sh"], shell=True, stdin=None, stdout=None, stderr=None, close_fds=True) proc.wait() # 阻塞等待子进程结束 print('Script 2 ended')
方案2:重定向子进程IO到空设备
将子进程的标准输入、输出、错误都重定向到DEVNULL,彻底切断与终端的关联:
import subprocess print('Script 2 started') subprocess.Popen( ["sh", "test.sh"], shell=True, stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True ) print('Script 2 ended')
方案3:移除多余的shell=True
直接调用sh执行脚本时,shell=True属于冗余设置,移除后可避免额外的shell层关联:
import subprocess print('Script 2 started') subprocess.Popen( ["sh", "test.sh"], stdin=subprocess.DEVNULL, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, close_fds=True ) print('Script 2 ended')
验证
任选一种修改后重新执行sc-2.py,脚本执行完成后终端会自动退出,无需手动按Ctrl+C。
内容的提问来源于stack exchange,提问作者abd
相关产品推荐
相关产品推荐

