Python - 如何使用管道调用 bash 命令?

标签 python popen subprocess

我在linux的命令行下可以正常运行这个:

$ tar c my_dir | md5sum

但是当我尝试用 Python 调用它时出现错误:

>>> subprocess.Popen(['tar','-c','my_dir','|','md5sum'],shell=True)
<subprocess.Popen object at 0x26c0550>
>>> tar: You must specify one of the `-Acdtrux' or `--test-label'  options
Try `tar --help' or `tar --usage' for more information.

最佳答案

你必须使用subprocess.PIPE,另外,为了拆分命令,你应该使用shlex.split()来防止在某些情况下出现奇怪的行为:

from subprocess import Popen, PIPE
from shlex import split
p1 = Popen(split("tar -c mydir"), stdout=PIPE)
p2 = Popen(split("md5sum"), stdin=p1.stdout)

但是要制作存档并生成其校验和,您应该使用 Python 内置模块 tarfilehashlib 而不是调用 shell 命令。

关于Python - 如何使用管道调用 bash 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7323859/

相关文章:

python - 设计一个简单的二项式分布会在 pymc 中抛出核心转储

python - 我可以在matplotlib中循环使用线条样式吗

Python LIST 函数不返回新列表

python - 以正确的方式终止一个进程及其子进程以 subprocess.popen 开始(windows 和 linux)

python - 需要通过用户输入(GPIO.input)结束子进程的循环

python - 如何巧妙地不忽略我的轴设置?

python - 在 Windows 上从 Python 脚本中终止由批处理文件启动的外部进程

python - python 中 subprocess.Popen() 打开的连接应该关闭吗

Python子进程: call an instance method

python - 当 Cisco 路由器的 ssh 命令产生大量输出时,subprocess.CalledProcessError 和 ssh 连接断开