【问题标题】:python not displaying executable output properlypython没有正确显示可执行输出
【发布时间】:2021-05-19 02:12:25
【问题描述】:

我正在使用代码在 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

我得到了正确的格式。

示例输出:

xxxxx xxxxx xx

期望的输出:

xxxxx
xxxxx
xx

【问题讨论】:

  • 在options中使用text=True,然后访问x.stdout获取返回的字节流。 x不是输出,是封装流程管理的对象。
  • 这可能是行尾转换问题。为确保这一点,您应该将 COSMO 可执行文件的输出重定向到一个文件,并使用十六进制编辑器检查文件的内容(或使用小型 Python 脚本将内容转储为 hexa)。
  • 不确定 COSMO bin 的作用,但请尝试添加到您的打印语句 print("{}\r".format(x)) 。请记住,subprocess.run() 返回一个 CompletedProcess 实例,也就是当 capture_outputtrue 标准输出和标准错误将被捕获时已完成的进程

标签: python linux shell subprocess executable


【解决方案1】:

您正在运行的代码将在一行上打印CompletedProcess 对象的人类可读表示,该对象包括但远不止是子进程的实际输出。

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'')

要实际只打印输出,请尝试

>>> 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)以及函数现在如何返回结果,以及调用者如何打印它(或用它做其他事情,如情况可能是)。通常,您希望函数返回结果而不是打印结果;这样可以更轻松地将它们重用于其他任务。

【讨论】:

    猜你喜欢
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-04-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-21
    相关资源
    最近更新 更多