Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get stderr from os.popen()?

If I call

os.popen('foo').read()

I want to capture

sh: foo: not found

as well.
I don't have the subprocess module since this is a minimal install on an embedded system.

popen3,4 doesn't work either:

 File "/usr/lib/python2.7/os.py", line 667, in popen3
import subprocess
ImportError: No module named subprocess

I suppose I could do

os.popen(command + " 2>&1").read()

to pipe it to stdout, but ideally I'd want to get it separately.

like image 868
Dmiters Avatar asked Feb 24 '16 20:02

Dmiters


People also ask

What does Popen return?

Python method popen() opens a pipe to or from command. The return value is an open file object connected to the pipe, which can be read or written depending on whether mode is 'r' (default) or 'w'.

How do I stop os Popen?

Both kill or terminate are methods of the Popen object. On macOS and Linux, kill sends the signal signal. SIGKILL to the process and terminate sends signal.

What is subprocess popen ()?

The subprocess module defines one class, Popen and a few wrapper functions that use that class. The constructor for Popen takes arguments to set up the new process so the parent can communicate with it via pipes. It provides all of the functionality of the other modules and functions it replaces, and more.


1 Answers

Since subprocess should be use in place of os.popen, you can do something like that

test.py:

from subprocess import PIPE, Popen

p = Popen("foo", shell=True, stdout=PIPE, stderr=PIPE)
stdout, stderr = p.communicate()
print "stdout: '%s'" % stdout
print "stderr: '%s'" % stderr

Now execute:

python test.py 
stdout: ''
stderr: '/bin/sh: 1: foo: not found
'

Notice the CR in stderr.

like image 84
wilfriedroset Avatar answered Sep 20 '22 12:09

wilfriedroset