Store output of subprocess.Popen call in a string [duplicate]

In Python 2.7 or Python 3 Instead of making a Popen object directly, you can use the subprocess.check_output() function to store output of a command in a string: from subprocess import check_output out = check_output([“ntpq”, “-p”]) In Python 2.4-2.6 Use the communicate method. import subprocess p = subprocess.Popen([“ntpq”, “-p”], stdout=subprocess.PIPE) out, err = p.communicate() out … Read more

A non-blocking read on a subprocess.PIPE in Python

fcntl, select, asyncproc won’t help in this case. A reliable way to read a stream without blocking regardless of operating system is to use Queue.get_nowait(): import sys from subprocess import PIPE, Popen from threading import Thread try: from queue import Queue, Empty except ImportError: from Queue import Queue, Empty # python 2.x ON_POSIX = ‘posix’ … Read more

Running shell command and capturing the output

In all officially maintained versions of Python, the simplest approach is to use the subprocess.check_output function: >>> subprocess.check_output([‘ls’, ‘-l’]) b’total 0\n-rw-r–r– 1 memyself staff 0 Mar 14 11:04 files\n’ check_output runs a single program that takes only arguments as input.1 It returns the result exactly as printed to stdout. If you need to write input … Read more