使用Python中的管道执行shell命令

2024-10-01 11:21:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我是Python新手,尝试过google搜索,但没有帮助。
我需要在管道中调用这样的命令(从mailq获取最早的待处理邮件):

mailq |grep "^[A-F0-9]" |sort -k5n -k6n |head -n 1

该命令在shell中工作。在

在Python中,我写了以下内容:

^{pr2}$

但我得到了这样的输出:

sort: write failed: standard output: Broken pipe\nsort: write error\n

想知道是什么导致了这样的错误?在


Tags: 命令管道google邮件shellsortgrephead
3条回答

我建议您使用这里写的子流程: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]

这是Python使用管道的方式。在

不要让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]

我认为这应该行得通:

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

打印响应的第一行

相关问题 更多 >