tags:

views:

27

answers:

3

Hello,

I want to assign the output of a command i run using os.system to a variable and prevent it from being output to the screen But, in the below code,the output is sent to the screen and the value printed for var is 0,which i guess signifies whether the command ran successfully or not. Any way to assign the command output to the variable and also stop it from being displayed on the screen ?

var = os.system("cat /etc/services")
print var #Prints 0

Please help Thank You

+5  A: 

From this question I asked a long time ago, what you may want to use is popen:

os.popen('cat /etc/services').read()

Edit: I'm told that subprocess is a much better way to solve this, so here's the corresponding code:

import subprocess

proc = subprocess.Popen(["cat", "/etc/services"], stdout=subprocess.PIPE, shell=True)
(out, err) = proc.communicate()
print "program output:", out
Chris Bunch
Thanks Chris..exactly what i was looking for ! :)
John
@Chris, a very long time ago that might have been the right way, but now it is to use `subprocess.Popen` instead!
Alex Martelli
@Alex: Fixed, thanks!
Chris Bunch
@Chris, +1, excellent fix, thanks.
Alex Martelli
A: 

The commands module is a reasonably high-level way to do this:

import commands
status, output = commands.getstatusoutput("cat /etc/services")

status is 0, output is the contents of /etc/services.

ianmclaury
A: 

You might also want to look at the subprocess module, which was built to replace the whole family of Python popen-type calls.

import subprocess
output = subprocess.check_output("cat /etc/services", shell=True)

The advantage it has is that there is a ton of flexibility with how you invoke commands, where the standard in/out/error streams are connected, etc.

Walter Mundt