Saltycrane logo

SaltyCrane Blog

Notes on Python, Django, and web development on Ubuntu Linux

     Posts tagged "processes"

How to capture stdout in real-time with Python

This solution is thanks to this article.

import subprocess

def myrun(cmd):
    """from http://blog.kagesenshi.org/2008/02/teeing-python-subprocesspopen-output.html
    """
    p = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
    stdout = []
    while True:
        line = p.stdout.readline()
        stdout.append(line)
        print line,
        if line == '' and p.poll() != None:
            break
    return ''.join(stdout)
... read more »

How to get stdout and stderr using Python's subprocess module

I wrote previously about how to get stdout and stderr using os.popen4. However, per the Python documentation, using the subprocess module is preferred:

The subprocess module allows you to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module intends to replace several other, older modules and functions, such as:

os.system
os.spawn*
os.popen*
popen2.*
commands.*

See the subprocess module documentation for more information.

Here is how to get stdout and stderr from a program using the subprocess module:

from subprocess import Popen, PIPE, STDOUT

cmd = 'ls /etc/fstab /etc ...
... read more »

How to use python and popen4 to capture stdout and stderr from a command

You can use popen to capture stdout from a command:
import os
stdout = os.popen("dir asdkfhqweiory")
print stdout.read()
And your output will be something like:
>>> ================================ RESTART ================================
>>>
Volume in drive C has no label.
Volume Serial Number is XXXXXXXX

Directory of C:\Python25


>>>
If you wanted the error message, popen won't give it to you. To capture both stdout and stderr, use popen4:
import os

(dummy, stdout_and_stderr) = os.popen4("dir asdkfhqweiory")
print stdout_and_stderr.read()
This will give you the following output (which includes the error message):
>>> ================================ RESTART ================================
>>>
Volume in drive C has no label.
Volume Serial Number is ...
... read more »
Created with Django | Hosted by Slicehost