如何在后台启动并运行外部脚本?
我尝试了这两种方法:
os.system("python test.py")
subprocess.Popen("python test.py", shell=True)
两种方法都需要等待 test.py 完成,这会阻止主进程。我知道“nohup”可以完成这项工作。有没有一种Python方法可以启动test.py或任何其他shell脚本并使其在后台运行?
假设 test.py 是这样的:
for i in range(0, 1000000):
print i
os.system() 或 subprocess.Popen() 都会阻塞主程序,直到显示 1000000 行输出。我想要的是让 test.py 静默运行并仅显示主程序输出。当 test.py 仍在运行时,主程序可能会停止。
I tried these two methods:
os.system("python test.py")
subprocess.Popen("python test.py", shell=True)
Both approaches need to wait until test.py finishes which blocks main process. I know "nohup" can do the job. Is there a Python way to launch test.py or any other shell scripts and leave it running in background?
Suppose test.py is like this:
for i in range(0, 1000000):
print i
Both os.system() or subprocess.Popen() will block main program until 1000000 lines of output displayed. What I want is let test.py runs silently and display main program output only. Main program may quie while test.py is still running.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
subprocess.Popen(["python", "test.py"])
应该可以工作。请注意,当主脚本退出时,作业可能仍会终止。在这种情况下,请尝试
subprocess.Popen(["nohup", "python", "test.py"])
subprocess.Popen(["python", "test.py"])
should work.Note that the job might still die when your main script exits. In this case, try
subprocess.Popen(["nohup", "python", "test.py"])