如何使用管道在子进程之间正确传递信息?

我试图通过Python脚本使用子进程获得一个简单的嵌套管道,但我得到的输出没有任何意义。

我尝试将diff的输出重定向到grep,并从grep重定向到wc,然后检查输出,但没有成功。

import subprocess

diff = subprocess.Popen(("diff", "-y", "--suppress-common-lines", "file1.py", "file2.py"), stdout=subprocess.PIPE)
diff.wait()
grep = subprocess.Popen(("grep", "'^'"), stdin=diff.stdout, stdout=subprocess.PIPE)
grep.wait()
output = subprocess.check_output(('wc', '-l'), stdin=grep.stdout)
print(output)

我希望这会导致file1.pyfile2.py之间的行数不同,但我得到的结果是

b'       0\n'

在命令行中,当我运行diff -y --suppress-common-lines file1.py file2.py | grep '^' | wc -l时,它返回一个整数。

转载请注明出处:http://www.cshftz.com/article/20230526/1129562.html