【问题标题】:Python subprocess using perl for formatting is giving incomplete output使用 perl 进行格式化的 Python 子进程给出不完整的输出
【发布时间】: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 子进程获取它的输出时:

  1. subprocess.Popen(cmnd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0].decode('UTF-8')

  2. check_output(cmnd,shell=True).decode('UTF-8')

  3. 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 commandPython Subprocess GrepPython subprocess run() is giving abnormal output [duplicate] 和许多其他问题,但我无法理解出了什么问题。

【问题讨论】:

    标签: python bash perl subprocess python-3.8


    【解决方案1】:

    您有报价问题。 """\1""" 表示 chr(0o1)。要生成字符串\1,您可以使用"""\\1"""\ 的其他实例也应该是 \\

    由于\ 的所有实例都需要转义,您也可以使用r"""\1"""

    其他问题:

    • \1\2 在正则表达式之外无论如何都是错误的。你应该使用$1$2

    • 这里没有多行文字。 "..."r"..." 就足够了。

    • 通过使用-0777 使perl 将整个文件视为一行,可以避免整个tr 业务。

    这给了我们:

    cmnd = "pacmd list-sink-inputs | perl -0777pe's/ *index: (\\d+).+?application\\.process\\.id = "([^\\n]+)"\\n.+?(?=index:|$)/$2:$1\\n/sag'"

    cmnd = r"pacmd list-sink-inputs | perl -0777pe's/ *index: (\d+).+?application\.process\.id = "([^\n]+)"\n.+?(?=index:|$)/$2:$1\n/sag'"

    但是这里为什么要使用 Perl 呢?你可以在 Python 中轻松地做同样的事情!

    【讨论】:

    • 哦,有问题了,非常感谢。使用三引号后,您的答案有效:cmnd = r"""bash-command""" worked。至于为什么我在 bash 命令中使用 Perl 而不是在 Python 中处理输出,Perl is way faster than Python for text processing。我试过了,但由于 min. 15 代表限制。
    猜你喜欢
    • 2019-05-19
    • 1970-01-01
    • 2013-08-18
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多