13

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.

Dmiters
  • 2,011
  • 3
  • 23
  • 31

1 Answers1

3

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.

wilfriedroset
  • 217
  • 1
  • 8
  • 1
    Would you care to elaborate as to why it is better? – user2589273 Jan 15 '20 at 15:56
  • 1
    @user2589273, (1) allows operating without a shell, which cures a series of security issues; (2) _whether or not_ operating without a shell, allows arguments to be passed out-of-band from the code being run, which lets someone write secure code even while using a shell (albeit requiring some effort). (3) offers vastly more flexibility -- lets one run a process in a different directory, perform redirections, control status of file descriptors, etc. (4) preferred as the replacement by upstream Python; as the current upstream docs say: ... – Charles Duffy Sep 21 '20 at 18:34
  • @user2589273, "*This is implemented using subprocess.Popen; see that class’s documentation for more powerful ways to manage and communicate with subprocesses*" -- so right now `os.popen` is just a less-powerful wrapper around `subprocess.Popen`; use the `subprocess` module and you get the full power. – Charles Duffy Sep 21 '20 at 18:34