繁体   English   中英

python 未正确显示可执行文件 output

[英]python not displaying executable output properly

我正在使用代码通过 Linux 终端中的 python 执行可执行文件。

我在 python 中使用的代码是

import subprocess


def executable_shell():
    # to run cosmo file     
    x=subprocess.run('cd .. && cd build &&  ./COSMO', shell=True, capture_output=True)
    print(x)

executable_shell()

这里 COSMO 是我的可执行文件 要运行这个 python 文件,我使用命令: $ python3 file.py

代码正在运行,但显示文件之间没有行间距,就像每个新行都从同一行开始而不是跳到新行。

但是如果我从终端以正常方式运行这个可执行文件

$ ./COSMO

我得到正确的格式。

示例 output:

xxxxx xxxxx xx

所需的 output:

xxxxx
xxxxx
xx

您正在运行的代码将在一行中打印CompletedProcess object 的人类可读表示,其中包括但包含的内容远不止子流程中的实际 output。

Python 3.7.2 (default, Mar 25 2020, 10:15:53) 
[Clang 11.0.3 (clang-1103.0.32.29)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import subprocess
>>> x = subprocess.run(['printf', '%s\n', 'foo', 'bar', 'baz'], capture_output=True)
>>> print(x)
CompletedProcess(args=['printf', '%s\n', 'foo', 'bar', 'baz'], returncode=0, stdout=b'foo\nbar\nbaz\n', stderr=b'')

要实际仅打印 output,请尝试

>>> print(x.stdout.decode())
foo
bar
baz

更好的是,让 Python 为您解码。

import subprocess


def executable_shell():
    # to run cosmo file     
    x = subprocess.run(
        # Just the command, as a list of arguments, so we can avoid shell=True
        ['./COSMO'],
        # Specify which directory to run it in
        cwd='../build',
        # Throw an exception if the command fails (optional but recommended)
        check=True,
        # Have Python decode the output as text instead of raw bytes
        text=True,
        # Capture output, as before
        capture_output=True)
    return x.stdout

print(executable_shell())

请注意我是如何添加text=True (并且还重构为使用check=True并摆脱shell=True )以及 function 现在如何返回结果,并且调用者打印它(或者根据情况用它做其他事情)是)。 通常,您希望函数返回结果而不是打印结果; 这使得将它们重用于其他任务变得更加容易。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM