编程技术网

关注微信公众号,定时推送前沿、专业、深度的编程技术资料。

 找回密码
 立即注册

QQ登录

只需一步,快速开始

极客时间

python无法正确显示可执行文件输出:python not displaying executable output properly

Daniel Brink Python 2022-5-11 10:56 7人围观

腾讯云服务器
python无法正确显示可执行文件输出的处理方法

我正在使用代码在Linux Terminal中通过python执行可执行文件.

I am using code to execute an executable file via python in Linux Terminal.

我在python中使用的代码是

The code I use in python is

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

Here COSMO is my executable file To run this python file I use command: $ python3 file.py

代码可以正常工作,但是显示文件之间没有行距,就像每个新行都从同一行开始而不是跳到新行一样.

The code is working but the display file is without line space between them, like each new line is starting on the same line rather than jumping to a new line.

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

But if I run this executable in the normal way from the terminal

$ ./COSMO 

我的格式正确.

示例输出:

xxxxx xxxxx xx 

所需的输出:

xxxxx xxxxx xx 

问题解答

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

The code you are running would print a human-readable representation of a CompletedProcess object which includes, but contains much more than, the actual output from your subprocess, on a single line.

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为您解码.

Better yet, have Python decode it for you.

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 )以及如何该函数现在返回结果,并且调用方将其打印出来(或对它进行其他操作(视情况而定)).通常,您希望函数返回结果而不是打印结果.这样可以更轻松地将它们重用于其他任务.

Notice how I added text=True (and also refactored to use check=True and get rid of shell=True) and how the function now returns the result, and the caller prints it (or does something else with it, as the case may be). Generally, you want functions to return results rather than print them; this makes it easier to reuse them for other tasks.

这篇关于python无法正确显示可执行文件输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程技术网(www.editcode.net)!

腾讯云服务器 阿里云服务器
关注微信
^