Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

This question already has an answer here:

I want execute netcat command from my python script, so I use the 'subprocess.Popen', but the problem is that the output of this command is directly printed in may shell console, i want o get him in a variable , so i can do some modification before printing it.

res = subprocess.Popen("nc -v 192.168.1.1 25", stdout=subprocess.PIPE, stderr=None, shell=True)
#output = res.communicate()
#output = str(output)
#print output
share|improve this question

marked as duplicate by tripleee, Charles Duffy, Corley Brigman, lennon310, Roman C Mar 13 '14 at 18:03

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
Have you tried also to redirect stderr? It is unlikely that nc would print directly to the terminal unless to prompt you for the password – J.F. Sebastian Mar 13 '14 at 17:21
    
    
i confirme that, when i use the ls -l in place of nc , it work, so the nc command put the result even if you dont use print command, what could be the solution?? – user3383192 Mar 13 '14 at 17:29
1  
For something simple like this why not just use a socket directly? – Keith Mar 13 '14 at 17:38

If you want make calling shell commands easy to yourself in Python use sh library.

In sh this would be:

  from sh import nc
  output = nc("-v", "192.168.1.1", "25")  # output is string of the command output

As always, installing Python libraries are recommended to do with virtualenv.

share|improve this answer

I use this to capture output from a system command, note that it will only get the last line. Modify around lastline as needed to get more:

def GetOutput(command):
    lastline = os.popen(command).readlines()
    result = lastline[0].rstrip()
    return result
share|improve this answer

Not the answer you're looking for? Browse other questions tagged or ask your own question.