子进程在 PyCharm 中正确显示 sys.stdout 但不在控制台中 [英] Subprocess displays sys.stdout correctly in PyCharm but not in the console
问题描述
我有一个小的 Python 程序,它从一个名为 commandwrapper
(它是 subprocess.popen
的包装器)的 pip
包中执行一个终端命令:https://pypi.python.org/pypi/commandwrapper/0.7).我还试图将实时输出捕获到控制台和文件中.
I have a small Python program that executes a terminal command from a pip
package called commandwrapper
(which is a wrapper for subprocess.popen
: https://pypi.python.org/pypi/commandwrapper/0.7). I am also trying to capture the real-time output to the console and to a file.
我有代码:
class Tee(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for f in self.files:
f.write(obj)
f.flush()
def flush(self) :
for f in self.files:
f.flush()
# Set the stdout/stderr to Tee()
out = open(stdout_log, 'w')
stdout_reset = sys.stdout
sys.stdout = Tee(sys.stdout, out)
process = commandwrapper.WrapCommand(command, shell=True) # Also tried False with same behaivor.
cmd = process.prepareToRun()
# Stream the output to the console and stdoutfiles
while cmd.poll() is None:
msg_out = cmd.stdout.readline()
sys.stdout.write(msg_out)
sys.stdout.flush()
out.close()
当我在 PyCharm 中运行它时,这非常有效.command
的输出被写入文件并实时显示在终端控制台上.
This works perfect when I run it in PyCharm. The output of command
is written to the file AND displayed on the terminal console in real-time.
但是,当我在终端中运行相同的代码时,控制台上没有显示任何输出.怎么会这样?stdout
在文件中被正确捕获,但没有写入控制台.
However, when I run the same code in a terminal, no output is displayed on the console. How can this be? The stdout
is correctly captured in a file, but nothing is written to the console.
谁能看出这段代码在 PyCharm 中运行良好并符合预期的任何原因,但没有向终端显示任何标准输出?我在这里不知所措.如果有的话,如果行为被逆转,我可以处理它.
Can anyone see any reason that this code would work well and as expected in PyCharm, but not display any stdout to the terminal? I'm at a loss here. If anything, I could deal with it if the behavior was reversed.
使用 OSX Yosemite 并运行 bash
.
Using OSX Yosemite and running bash
.
推荐答案
您需要更改投票的逻辑,我使用了 Popen,但如果您愿意,也可以使用包装器:
You need to change the logic where you have poll, I used Popen but you can use the wrapper if you prefer:
out = open(stdout_log, 'w')
stdout_reset = sys.stdout
sys.stdout = Tee(sys.stdout, out)
from subprocess import Popen,PIPE,STDOUT
process = Popen([list_of_cmds],stdout=PIPE,stderr=STDOUT)
# Stream the output to the console and stdoutfiles
for line in iter(process.stdout.readline,""):
sys.stdout.write(line)
out.close()
应用相同的逻辑适用于 commandwrapper
库:
Applying the same logic works with the commandwrapper
lib:
process = commandwrapper.WrapCommand(command, shell=True) # Also tried False with same behaivor.
cmd = process.prepareToRun()
# Stream the output to the console and stdoutfiles
for line in iter(cmd.stdout.readline,""):
sys.stdout.write(line)
这篇关于子进程在 PyCharm 中正确显示 sys.stdout 但不在控制台中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!