我用subprocess
模块调用不同的进程.但是,我有一个问题.
在以下代码中:
callProcess = subprocess.Popen(['ls', '-l'], shell=True)
Run Code Online (Sandbox Code Playgroud)
和
callProcess = subprocess.Popen(['ls', '-l']) # without shell
Run Code Online (Sandbox Code Playgroud)
两者都有效.阅读文档后,我开始知道这shell=True
意味着通过shell执行代码.这意味着在缺席的情况下,该过程将直接启动.
那么我应该更喜欢我的情况 - 我需要运行一个进程并获得其输出.从shell内部或外部调用它有什么好处.
我想用一个程序启动几个子进程,即一个模块foo.py
启动几个实例bar.py
.
由于我有时必须手动终止进程,因此我需要进程id来执行kill命令.
即使整个设置非常"脏" pid
,如果过程是通过启动进行的,还是有一种很好的pythonic方式来获取进程os.system
吗?
foo.py:
import os
import time
os.system("python bar.py \"{0}\ &".format(str(argument)))
time.sleep(3)
pid = ???
os.system("kill -9 {0}".format(pid))
Run Code Online (Sandbox Code Playgroud)
bar.py:
import time
print("bla")
time.sleep(10) % within this time, the process should be killed
print("blubb")
Run Code Online (Sandbox Code Playgroud) 在使用该subprocess.call
方法的Python中是否有更高效或更快的效果?我注意到一年前有一个SO问题(Python子进程模块比命令(弃用)慢得多)除了由于Python删除了替代品而导致折旧,所以我想看看这是否是现在唯一的,因此最快意味着从Python中调用shell命令.具体来说,我正在运行以下命令:
subprocess.call( "foo" 的,壳=真)
或者我应该使用os
?
谢谢.