Python 的 subprocess.call() 和 Bash 流在语义上是否不同?

Are Python's subprocess.call() and Bash streams semantically different?

来自bash:

$ python script.py < input.txt 2> stderr.txt > stdout.txt

在Python中:

import subprocess
subprocess.call(["python", "script.py"],
                stdin=open('input.txt', 'rb'),
                stdout=open('stdout.txt', 'wb'),
                stderr=open('stderr.txt', 'wb'))

假设有效 input.txtpython 有效且在路径中等,对于简单情况,这些行为相同。

在某些情况下,shell 版本的行为可能与 Python 版本不同?

Are there any cases where the shell version could behave differently than the Python version?

这取决于您想要的效果。程序执行和流重定向在 shell 行中与在 Python 脚本中执行完全相同的操作。另一方面,shell 确实会影响子进程的一些其他更改,例如将其放入新的进程组并使其成为终端上的前台进程组。

EDIT:在您的评论中,存在 差异,但过程组更改是我唯一的一个至少马上就能想到。这确实是一个非常微小的差异,不进行相当高级的作业控制的程序不会受到任何影响。至少内存限制或任何性能影响肯定没有变化。一般来说,至少 广大 大多数程序没有差异。

当然,您也可以从 Python 中执行相同的进程组更改:请参阅 os.setpgid()os.tcsetpgrp()