7

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 ?

0

4 Answers 4

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

new result stored at variable a :)

Sign up to request clarification or add additional context in comments.

1 Comment

The correct one did not worked for me but this one was perfect!
6
import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, error = p.communicate()

9 Comments

Would not the third line you mentioned be under parenthesis ? Like, (out, error) = p.communicate() and then say print "the result is: ", out
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', error
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 ?
Please edit and surround code with backticks ``` so it's readable.
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.
|
1
import subprocess
p = subprocess.Popen('my_command', stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
out, error = p.communicate()

Comments

0
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

This also solves my problem ; but @agf 's answer was a one liner

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.