【发布时间】:2021-09-20 13:05:03
【问题描述】:
我在读取 python 子进程命令的输出时遇到问题。
我想读取其输出的 bash 命令:
pacmd list-sink-inputs | tr '\n' '\r' | perl -pe 's/ *index: ([0-9]+).+?application\.process\.id = "([^\r]+)"\r.+?(?=index:|$)/\2:\1\r/g' | tr '\r' '\n'
当我通过 bash 运行它时,我得到了预期的输出:
4 sink input(s) available.
6249:72
20341:84
20344:86
20350:87
当我尝试通过运行其中一个的 python 子进程获取它的输出时:
-
subprocess.Popen(cmnd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode('UTF-8') -
check_output(cmnd,shell=True).decode('UTF-8') -
subprocess.run(cmnd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).stdout.decode('utf-8')
在哪里cmnd = """pacmd list-sink-inputs | tr '\n' '\r' | perl -pe 's/ *index: ([0-9]+).+?application\.process\.id = "([^\r]+)"\r.+?(?=index:|$)/\2:\1\r/g' | tr '\r' '\n'"""
它给出以下输出:
'4 sink input(s) available.\n\x02:\x01\n\x02:\x01\n\x02:\x01\n\x02:\x01\n'
这是无意的,因为它没有 6249:72 等。我想要的数字。甚至 stderr 也是空白,返回码也是 0。
我能找到的唯一解决方法是将 bash 输出重定向到文本文件,然后通过我不想使用的 python 读取文本文件,因为这是不必要的文件 IO。
我已经经历了Missing output from subprocess command、Python Subprocess Grep、Python subprocess run() is giving abnormal output [duplicate] 和许多其他问题,但我无法理解出了什么问题。
【问题讨论】:
标签: python bash perl subprocess python-3.8