Python - 如何使用管道调用 bash 命令? [英] Python - How to call bash commands with pipe?

查看:122
本文介绍了Python - 如何使用管道调用 bash 命令?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以在 Linux 的命令行上正常运行:

$ tar c my_dir |md5sum

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

<预><代码>>>>subprocess.Popen(['tar','-c','my_dir','|','md5sum'],shell=True)<subprocess.Popen 对象在 0x26c0550>>>>tar:您必须指定-Acdtrux"或--test-label"选项之一试试 `tar --help' 或 `tar --usage' 以获得更多信息.

解决方案

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

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

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

I can run this normally on the command line in Linux:

$ tar c my_dir | md5sum

But when I try to call it with Python I get an error:

>>> 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.

解决方案

You have to use subprocess.PIPE, also, to split the command, you should use shlex.split() to prevent strange behaviours in some cases:

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

But to make an archive and generate its checksum, you should use Python built-in modules tarfile and hashlib instead of calling shell commands.

这篇关于Python - 如何使用管道调用 bash 命令?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆