Python的3​​.4.3 subprocess.Popen get命令的输出,而不管? [英] Python 3.4.3 subprocess.Popen get output of command without piping?

查看:255
本文介绍了Python的3​​.4.3 subprocess.Popen get命令的输出,而不管?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想一个命令给一个变量输出分配没有命令以为它正在管道。这样做的原因是,有问题的命令给未格式化的文本作为输出,如果被它的管道,但它给彩色格式的文本,如果它被从终端上运行。我需要这种颜色格式的文本。

I am trying to assign the output of a command to a variable without the command thinking that it is being piped. The reason for this is that the command in question gives unformatted text as output if it is being piped, but it gives color formatted text if it is being run from the terminal. I need to get this color formatted text.

到目前为止,我已经尝试了几件事情。我已经试过POPEN像这样:

So far I've tried a few things. I've tried Popen like so:

output = subprocess.Popen(command, stdout=subprocess.PIPE)
output = output.communicate()[0]
output = output.decode()
print(output)

这将让我打印输出,但它给我的格式化输出,我得到当命令管道。这是有道理的,因为我在Python code管道在这里它。不过我很好奇,如果有分配此命令的输出方式,直接把一个变量,而无需运行本身的管道版本的命令。

This will let me print the output, but it gives me the unformatted output that I get when the command is piped. That makes sense, as I'm piping it here in the Python code. But I am curious if there is a way to assign the output of this command, directly to a variable, without the command running the piped version of itself.

我也曾尝试以下的版本,它依赖于check_output来代替:

I have also tried the following version that relies on check_output instead:

output = subprocess.check_output(command)
output = output.decode()
print(output)

和我再次得到相同的格式化输出,该命令返回时,命令管道。

And again I get the same unformatted output that the command returns when the command is piped.

有没有办法让格式化输出,输出命令通常会从终端,但是当没有被管道输送呢?

Is there a way to get the formatted output, the output the command would normally give from the terminal, when it is not being piped?

推荐答案

使用 Pexpect的

2.py:

import sys

if sys.stdout.isatty():
    print('hello')
else:
    print('goodbye')

子:

import subprocess

p = subprocess.Popen(
    ['python3.4', '2.py'],
    stdout=subprocess.PIPE
)

print(p.stdout.read())

--output:--
goodbye

Pexpect的:

pexpect:

import pexpect

child = pexpect.spawn('python3.4 2.py')

child.expect(pexpect.EOF)
print(child.before)  #Print all the output before the expectation.

--output:--
hello

这是的grep --colour =汽车

import subprocess

p = subprocess.Popen(
    ['grep', '--colour=auto', 'hello', 'data.txt'],
    stdout=subprocess.PIPE
)

print(p.stdout.read())

import pexpect

child = pexpect.spawn('grep --colour=auto hello data.txt')
child.expect(pexpect.EOF)
print(child.before)

--output:--
b'hello world\n'
b'\x1b[01;31mhello\x1b[00m world\r\n'

这篇关于Python的3​​.4.3 subprocess.Popen get命令的输出,而不管?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆