用一些例子来扩展@otorrillas 的答案。
假设您有一个简短的脚本,您只关心它是否成功*,并且您只想现在执行并等待结果。例如,假设您想向远程计算机发送单个 ping。 call 最适合你:
res = call(['ping', '127.0.0.1', '-c', '1', '-W', '1'])
# res is 0 if the ping succeeded, non-zero if it failed.
现在说你有一个你想假设会成功的命令,并且会给你一些你想用于某事的输出。 check_output 是给你的。也许是一个颠覆命令:
svn_output = check_output(['svn', 'info', path_to_my_working_copy])
# svn_output now contains the svn info output. If it failed, an
# exception is thrown which more easily allows you to give
# responsibility of that failure to whoever passed us the wrong
# path_to_my_working_copy.
一般来说,如果您的用例不只是属于这些类别之一,您可能最终会使用Popen。
一个简单的用例可能是,假设您有一个要启动的守护进程,但随后与您的 python 进程一起运行。现在你使用Popen:
my_proc = Popen(['my-daemon'])
# We're going to go and do something else now, but want to make sure
# my_proc dies when we do.
import atexit
atexit.register(my_proc.kill)
注意:如果您使用Popen raw,您必须确保终止进程,可能使用atexit,如我所说明的。
* “非零”退出状态仅表示进程失败。归因于Tolstoy 的一句著名的计算机科学名言是“快乐的过程都是相似的;每个不快乐的过程都以自己的方式不快乐”,即一个过程只有一种快乐的方式:返回 0。其他一切都不快乐,但是不开心的方式有很多。