我在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 内置模块 tarfile
和 hashlib
而不是调用 shell 命令。
关于Python - 如何使用管道调用 bash 命令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7323859/