我有從pip
包稱爲commandwrapper
(其是用於subprocess.popen
的包裝:https://pypi.python.org/pypi/commandwrapper/0.7)執行一個終端命令小Python程序。我也試圖捕獲到控制檯和文件的實時輸出。子過程顯示正確在PyCharm但不是sys.stdout來在控制檯
我的代碼:
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
的輸出寫入文件並實時顯示在終端控制檯上。
但是,當我在終端中運行相同的代碼時,控制檯上沒有顯示任何輸出。怎麼會這樣? stdout
已正確捕獲到文件中,但沒有任何內容寫入控制檯。
任何人都可以看到任何理由,這個代碼將工作正常,並在PyCharm預期,但不顯示任何標準輸出終端?我在這裏不知所措。如果有的話,如果行爲逆轉,我可以處理它。
使用OSX Yosemite並運行bash
。
什麼是'commandwrapper.WrapCommand'? –
它是'subprocess.popen'的包裝。我添加了上面的'pip'包的鏈接。感謝您指出了這一點。 – Brett
什麼操作系統和shell? –