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

I have a Windows console application that returns some text. I want to read this text in a Python script. I tried reading it using os.system, but it does not work correctly.

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

Assuming test.exe returns β€œbar”, I want foo to be set to β€œbar”. But what happens, it prints a β€œbar” on the console, and the foo variable is set to 0.

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

+4
source share
2 answers

Please use a subprocess.

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

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

+8
source

A WARNING. This only works on UNIX systems.

I find that subprocess is redundant when all you need is output for capture. I recommend using commands.getoutput() :

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

Technically, it just makes popen() on your behalf, but it is much simpler for this basic purpose.

BTW, os.system() does not return the result of the command, it returns the exit status, so it does not work for you.

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

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

Source: https://habr.com/ru/post/972886/


All Articles