管道和子流程模块之间有什么区别?

时间:2019-05-17 01:09:53

标签: python file subprocess

我对管道和子流程模块感到困惑。

这是我的代码:

import pipes
import subprocess


with open('123.txt', 'w') as f:
    f.write('a line 1\n')
    f.write('a line 2\n')

t = pipes.Template()
t.append('grep a', '--')
f = t.open('123.txt', 'r')
print(f.readlines())

with open('123.txt', 'r') as f:
    p = subprocess.Popen('grep a', stdin=f, stdout=subprocess.PIPE, shell=True, universal_newlines=True)

print(p.readlines())

它们的输出完全相同:

['a line 1\n', 'a line 2\n']
['a line 1\n', 'a line 2\n']

我的问题是:

  1. 这两个模块之间有什么区别。

  2. 我可以通过subprocess.PIPE(stdin)编写字符串,然后重定向到另一个subprocess.PIPE(stdout)。在这种情况下,我应该在args中使用什么subprocess.Popen

1 个答案:

答案 0 :(得分:2)

粘贴subprocesspipes是* NIX特定的,几乎没有维护,并且是基于os.system可以替换的半弃用的os.pipe / subprocess原语的。尽管subprocess没有具体提到pipes模块,但它确实提供了Replacing shell pipelines的示例,该示例将处理您似乎关心的情况,而不会在{{1 }}(由于它是基于pipes / os.system构建的),os.popen可以更安全,更快捷(如果您不使用subprocess的话),并且更便于携带启动。