python输出重定向到窗口_[python]重定向输出
本文作者:riag
本文出處:http://blog.csdn.net/riag
聲明: 本文可以不經(jīng)作者同意, 任意復(fù)制, 轉(zhuǎn)載, 但任何對(duì)本文的引用都請(qǐng)保留文章開始前三行的作者, 出處以及聲明信息. 謝謝.
調(diào)用一個(gè)控制臺(tái)程序,獲取它的標(biāo)準(zhǔn)輸出,或把它的標(biāo)準(zhǔn)輸出重定向到界面上,這里只介紹如何獲取它的標(biāo)準(zhǔn)輸出,因?yàn)樵矶家粯拥摹?/p>
使用python2.5的subprocess模塊來(lái)實(shí)現(xiàn)。
import sys
import subprocess
def RunShellWithReturnCode(command, print_output=False,
universal_newlines=True):
"""Executes a command and returns the output from stdout and the return code.
Args:
command: Command to execute.
print_output: If True, the output is printed to stdout.
If False, both stdout and stderr are ignored.
universal_newlines: Use universal_newlines flag (default: True).
Returns:
Tuple (output, return code)
"""
p = subprocess.Popen(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE,
shell=use_shell, universal_newlines=universal_newlines)
if print_output:
output_array = []
while True:
line = p.stdout.readline()
if not line:
break
print line.strip("/n")
output_array.append(line)
output = "".join(output_array)
else:
output = p.stdout.read()
p.wait()
errout = p.stderr.read()
#if print_output and errout:
# print >>sys.stderr, errout
p.stdout.close()
p.stderr.close()
return output, p.returncode
def RunShell(command, silent_ok=False, universal_newlines=True,
print_output=False):
data, retcode = RunShellWithReturnCode(command, print_output,
universal_newlines)
if retcode:
ErrorExit("Got error status from %s:/n%s" % (command, data))
if not silent_ok and not data:
ErrorExit("No output from %s" % command)
return data
上面的代碼來(lái)自于 開源的代碼審查工具 rietveld 的代碼,其中RunShellWithReturnCode函數(shù) 就是返回控制臺(tái)的標(biāo)準(zhǔn)輸出和返回結(jié)果
總結(jié)
以上是生活随笔為你收集整理的python输出重定向到窗口_[python]重定向输出的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python3 log_Python3
- 下一篇: python 彩票 遗漏值_荐Pytho