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

0x4*_*9D1 3 python stdout pipe mail-queue

我是Python新手,尝试过谷歌搜索,但没有帮助..
我需要在管道中调用此类命令(从mailq获取最旧的待处理邮件):

mailq |grep "^[A-F0-9]" |sort -k5n -k6n |head -n 1
Run Code Online (Sandbox Code Playgroud)

该命令在 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]
Run Code Online (Sandbox Code Playgroud)

但我得到这样的输出:

排序: 写入失败: 标准输出: 管道损坏\n排序: 写入错误\n

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

UN4*_*UN4 5

我认为这应该有效:

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
Run Code Online (Sandbox Code Playgroud)

打印响应的第一行