Skip to main content
 首页 » 编程设计

python之在 Python 中使用管道执行 shell 命令

2025年05月04日26dflying

我是 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] 

但是我得到这样的输出:

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

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

请您参考如下方法:

我认为这应该可行:

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 

打印响应的第一行