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 ?
4 Answers
a=os.popen("your command").read()
new result stored at variable a :)
1 Comment
VicoMan
The correct one did not worked for me but this one was perfect!
import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = p.communicate()
9 Comments
Ashutosh Narayan
Would not the third line you mentioned be under parenthesis ? Like, (out, error) = p.communicate() and then say print "the result is: ", out
agf
No, in Python, you don't need the parenthesis. Tuples can be implicitly created and automatically packed and unpacked. Yes, you can then do
print 'The output was', out, 'and the error was', errorAshutosh Narayan
OK, got that. Is this is the right syntax to execute the following netstat command -> result = subprocess.Popen(["netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"], stdout=subprocess.PIPE, stderr= subprocess.PIPE) ? I get an error : File "/usr/lib/python2.7/subprocess.py", line 672, in init errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1202, in _execute_child raise child_exception OSError: [Errno 2] No such file or directory Why am I getting so ?
agf
Please edit and surround code with backticks ``` so it's readable.
agf
try this
result = subprocess.Popen('''sh -c "netstat -plant | awk \'{print $4}\' | grep %s:%s | wc -l' %(ip,port)"''') Edit: or try it with shell=True as @Jakob-Bowyer suggested below. Needed because you're not just running one command, but instead are using the pipe | feature of the shell. |
netstat -plant | awk '{print $4}' | grep %s:%s | wc -l
You can use Python to do the splitting, grepping and counting:
process = subprocess.Popen(['netstat', '-plant'], stdout=subprocess.PIPE)
num_matches = 0
host_and_port = "%s:%s" % (ip, port)
for line in process.stdout:
parts = line.split()
if parts[3] == host_and_port: # or host_and_port in parts[3]
num_matches += 1
print num_matches
1 Comment
Ashutosh Narayan
This also solves my problem ; but @agf 's answer was a one liner