Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to store the return value of os.system that it has printed to stdout in python? [duplicate]

Tags:

python

I am writing a python script which checks for number of active connections for a particular IP / port. For this I use os.system( 'my_command') to grab the output. os.system returns the exit status of the command I've passed it (0 means the command returned without error). How can I store this value which os.system throws to STDOUT in a variable ? So that this variable can used later in the function for counter. Something like subprocess, os.popen can help. Can someone suggest ?

like image 426
Ashutosh Narayan Avatar asked Jul 19 '11 10:07

Ashutosh Narayan


3 Answers

a=os.popen("your command").read()

new result stored at variable a :)

like image 200
jack-X Avatar answered Oct 12 '22 05:10

jack-X


import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = p.communicate()
like image 34
agf Avatar answered Oct 12 '22 07:10

agf


import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, error = p.communicate()
like image 1
Jakob Bowyer Avatar answered Oct 12 '22 07:10

Jakob Bowyer