繁体   English   中英

打印 stdout 子进程 Popen 并保留格式

[英]Print stdout subprocess Popen and retain formatting

我正在使用subprocess.Popen来调用安装脚本。 但是,当我通过print将输出通过管道传输到终端时,它会丢失安装脚本输出中的任何格式。 例如,所有终端颜色都消失了,下载进度条出现在多行。

这是我的代码:

process = subprocess.Popen(
    [script],
    shell=True,
    cwd=script_dir,
    universal_newlines=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.STDOUT,
    env={
        'WORKSPACE': build_dir
    })
with process.stdout:
    for line in iter(process.stdout.readline, b''):
        print(line)

以及输出示例(通常显示为进度条):

You need to run "nvm install 4.2.2" to install it before using it.
Downloading and installing node v4.2.2...
Downloading https://nodejs.org/dist/v4.2.2/node-v4.2.2-darwin-x64.tar.gz...

                                                                          0.0%
                                                                          1.0%
###                                                                        4.6%
#######                                                                   10.5%
#############                                                             18.8%
###################                                                       26.5%
########################                                                  34.1%
##############################                                            41.9%
###################################                                       49.7%
#########################################                                 57.4%
##############################################                            65.2%
####################################################                      73.0%
##########################################################                80.8%
###############################################################           88.5%
#####################################################################     96.3%
######################################################################## 100.0%

无需调用“iter”。 事实上,当我尝试这个建议时它会抱怨,因为它需要一个字符串,而不是字节。

这可以重定向完全相同的输出:

process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, universal_newlines=True)
for line in process.stdout:
    sys.stdout.write(line)
    sys.stdout.flush()

print语句在末尾打印额外的换行符。 使用sys.stdout.write代替:

import sys

...    

with process.stdout:
    for line in iter(process.stdout.readline, b''):
        sys.stdout.write(line)  # <--
        sys.stdout.flush()      # <--

顺便说一句,除非您想在程序中处理输出,否则您可以只使用subprocess.call而无需捕获 stdout、stderr 输出:

subprocess.call(
    [script],
    shell=True,
    cwd=script_dir,
    env={
        'WORKSPACE': build_dir
    })

暂无
暂无

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

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