-1

I want to run my command and capture stdout realtime:

import subprocess
import shlex
cmd='my command'
args=shlex.split(cmd)    
com=subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
com.stdout.flush()
for line in com.stdout.read()
    print line

But there is nothing as output...

1
  • 1
    Maybe this or this? Commented Nov 14, 2015 at 13:06

2 Answers 2

1

read() reads until EOF (which does not usually happen until subprocess exit), to get more 'realtime' at least read by lines via readline() in a loop

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

Comments

0

Any object connected to a file descriptor can be passed to subprocess.Popen including sys.stdout!

com=subprocess.Popen(args,stdout=sys.stdout,stderr=sys.stderr)

Note that this may not work in some python shells.

5 Comments

Error: IndexError: list index out of range @ppperry
That error makes no sense in the context of my answer, which does not do any kind of list indexing. Please show the full traceback
This is output: ` tcpdump=subprocess.Popen(args,stdout=sys.stdout,stderr=sys.stderr) File "/usr/lib/python2.7/subprocess.py", line 710, in init errread, errwrite) File "/usr/lib/python2.7/subprocess.py", line 1206, in _execute_child executable = args[0] `
You are passing an empty list to the subprocess.Popen constructor. This has nothing to do with output redirection.
there is no need to use stdout=sys.stdout. By default the standard output is inherited i.e., if you you don't pass stdout parameter then the child process prints to the same place as the parent Python script (unless sys.stdout is replaced incorrectly).

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.