我是Python新手,试过谷歌搜索,但没有帮助.
我需要在管道中调用这些命令(从mailq获取最古老的挂起邮件):
mailq |grep "^[A-F0-9]" |sort -k5n -k6n |head -n 1该命令在shell中工作。
在Python中,我写了以下内容:
p = subprocess.Popen( 'mailq |grep \"^[A-F0-9]\" |sort -k5n -k6n |head -n 1', shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
response = p.communicate()[0]但是我得到了这样的输出:
排序:写入失败:标准输出:断开管道\n排序:写入错误\n
想知道是什么导致了这样的错误?
发布于 2016-12-20 09:12:03
我认为这应该是可行的:
p = subprocess.Popen( 'mailq |grep \"^[A-F0-9]\" |sort -k5n -k6n |head -n 1', shell=True,
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
response = p.stdout.readlines(-1)[0]
print response打印响应的第一行。
发布于 2016-12-20 09:05:25
与其让shell负责将命令拆分为多个进程并对它们进行管道处理,不如自己动手。请参见here如何将一个子进程流输送到另一个子进程。
这样,您就可以查找每个步骤的输出(例如,将stdout路由到您的stdout,只是为了调试),并确定您的整个工作流是否正常。
它看起来有点像这样:
mail_process = subprocess.Popen('mailq', stdin=PIPE, stdout=PIPE, stderr=STDOUT)
grep_process = subprocess.Popen(['grep', '\"^[A-F0-9]"'], stdin=mail_process.stdout, stdout=PIPE, stderr=STDOUT]
...
head_process = subprocess.Popen(["head", ...], ...)
head_process.communicate()[0]发布于 2016-12-20 09:05:47
我建议您使用下面所写的子进程:http://kendriu.com/how-to-use-pipes-in-python-subprocesspopen-objects
ls = subprocess.Popen('ls /etc'.split(), stdout=subprocess.PIPE)
grep = subprocess.Popen('grep ntp'.split(), stdin=ls.stdout, stdout=subprocess.PIPE)
output = grep.communicate()[0]这是使用管道的节奏式方法。
https://stackoverflow.com/questions/41238273
复制相似问题