[New-bugs-announce] [issue1631] Send output from subprocess.Popen objects to any object with a write() method

Nishkar Grover report at bugs.python.org
Sat Dec 15 02:01:33 CET 2007


New submission from Nishkar Grover:

It would be nice if we could send output from subprocess.Popen objects
to any object with a write() method.

Consider the following example, where I'm using Python 2.4.4 (#1, Jun 28
2007, 15:10:17, GCC 3.4.3 on linux2)...

>>>
>>> fh = open('/tmp/file.txt', 'w')
>>> cmdObj = subprocess.Popen('uname -a', shell=True, stdout=fh)
>>> fh.close()
>>> fh = open('/tmp/file.txt', 'r')
>>> fh.read()
'Linux northstar 2.6.9-42.0.2.IT111843.1.ELsmp #1 SMP Fri May 11
18:50:54 EDT 2007 x86_64 x86_64 x86_64 GNU/Linux\n'
>>>

That demonstrates that I can successfully send the stdout output from my
subprocess.Popen object to a file handle.

I tried to send that output to a custom object that has a write() method...

>>>
>>> class Foo(object):
...     def write(self, msg):
...         sys.stdout.write('*** %s ***' % msg.rstrip() + os.linesep)
...         sys.stdout.flush()
...     def close(self):
...         pass
...
>>>
>>> foo = Foo()
>>>
>>> cmdObj = subprocess.Popen('uname -a', shell=True, stdout=foo)
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "/rel/lang/python/2.4.4-4/lib/python2.4/subprocess.py", line 534,
in __init__
    (p2cread, p2cwrite,
  File "/rel/lang/python/2.4.4-4/lib/python2.4/subprocess.py", line 840,
in _get_handles
    c2pwrite = stdout.fileno()
AttributeError: 'Foo' object has no attribute 'fileno'
>>>

so I gave it a fileno() method that returns None...

>>>
>>> class Foo(object):
...     def write(self, msg):
...         sys.stdout.write('*** %s ***' % msg.rstrip() + os.linesep)
...         sys.stdout.flush()
...     def close(self):
...         pass
...     def fileno(self):
...         return None
...
>>>
>>> foo = Foo()
>>>
>>> cmdObj = subprocess.Popen('uname -a', shell=True, stdout=foo)
>>> Linux northstar 2.6.9-42.0.2.IT111843.1.ELsmp #1 SMP Fri May 11
18:50:54 EDT 2007 x86_64 x86_64 x86_64 GNU/Linux
>>>

Notice that the output went straight to the console and bypassed my
'foo' object's write() method.

----------
components: Library (Lib)
messages: 58646
nosy: ngrover
severity: normal
status: open
title: Send output from subprocess.Popen objects to any object with a write() method
type: behavior
versions: Python 2.4

__________________________________
Tracker <report at bugs.python.org>
<http://bugs.python.org/issue1631>
__________________________________


More information about the New-bugs-announce mailing list