Python 2.6: reading data from a Windows Console application. (os.system?)

让人想犯罪 __ 提交于 2019-12-21 17:51:12

问题


I have a Windows console application that returns some text. I want to read that text in a Python script. I have tried reading it by using os.system, but it is not working properly.

import os
foo = os.system('test.exe')

Assuming that test.exe returns "bar", I want the variable foo to be set to "bar". But what happens is, it prints "bar" on the console and the variable foo is set to 0.

What do I need to do to get the behavior I want?


回答1:


Please use subprocess

import subprocess
foo = subprocess.Popen('test.exe',stdout=subprocess.PIPE,stderr=subprocess.PIPE)

http://docs.python.org/library/subprocess.html#module-subprocess




回答2:


WARNING: This only works on UNIX systems.

I find that subprocess is overkill when all you want is output to be captured. I recommend the use of commands.getoutput():

>>> import commands
>>> foo = commands.getoutput('bar')

Technically it's just doing a popen() on your behalf, but it's a lot simpler for this basic purpose.

BTW, os.system() does not return the output of the command, it only returns the exit status, which is why it is not working for you.

Alternatively, if you require both the exit status and the command output, use commands.getstatusoutput(), which returns a 2-tuple of (status, output):

>>> foo = commands.getstatusoutput('bar')
>>> foo
(32512, 'sh: bar: command not found')


来源:https://stackoverflow.com/questions/1885776/python-2-6-reading-data-from-a-windows-console-application-os-system

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!