-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...

MLSC
  • 5,872
  • 8
  • 55
  • 89
  • 1
    Maybe [this](http://stackoverflow.com/questions/803265/getting-realtime-output-using-subprocess) or [this](http://stackoverflow.com/questions/1606795/catching-stdout-in-realtime-from-subprocess)? – Remi Guan Nov 14 '15 at 13:06

2 Answers2

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

Vasfed
  • 18,013
  • 10
  • 47
  • 53
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.

pppery
  • 3,731
  • 22
  • 33
  • 46
  • Error: IndexError: list index out of range @ppperry – MLSC Nov 14 '15 at 13:37
  • 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 – pppery Nov 14 '15 at 13:39
  • 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] ` – MLSC Nov 14 '15 at 13:41
  • You are passing an empty list to the `subprocess.Popen` constructor. This has nothing to do with output redirection. – pppery Nov 14 '15 at 13:43
  • 2
    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). – jfs Nov 16 '15 at 01:00