我有一个Windows控制台应用程序返回一些文本。 我想读一个Python脚本中的文本。 我已经尝试使用os.system读取它,但它不能正常工作。
import os foo = os.system('test.exe')
假设test.exe返回“bar”,我想把variablesfoo设置为“bar”。 但是会发生什么呢,它会在控制台上打印“bar”,并将variablesfoo设置为0。
我需要做些什么来获得我想要的行为?
请使用子进程
import subprocess foo = subprocess.Popen('test.exe',stdout=subprocess.PIPE,stderr=subprocess.PIPE)
http://docs.python.org/library/subprocess.html#module-subprocess
警告: 这只适用于UNIX系统。
当你想要的所有输出被捕获时,我发现subprocess
是过度的。 我建议使用commands.getoutput()
:
>>> import commands >>> foo = commands.getoutput('bar')
从技术上讲,这只是代表你做了一个popen()
,但这个基本目的要简单得多。
顺便说一句, os.system()
不返回命令的输出,它只返回退出状态,这就是为什么它不适合你。
或者,如果您需要退出状态和命令输出,请使用commands.getstatusoutput()
,它将返回(状态,输出)的2元组:
>>> foo = commands.getstatusoutput('bar') >>> foo (32512, 'sh: bar: command not found')