I'm working with subprocess
package to call some external console commands from a python script, and I need to pass file handlers to it to get stdout and stderr back separately. The code looks like this roughly:
import subprocess
stdout_file = file(os.path.join(local_path, 'stdout.txt'), 'w+')
stderr_file = file(os.path.join(local_path, 'stderr.txt'), 'w+')
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
This works fine and txt files with relevant output are getting created. Yet it would be nicer to handle these outputs in memory omitting files creation. So I used StringIO package to handle it this way:
import subprocess
import StringIO
stdout_file = StringIO.StringIO()
stderr_file = StringIO.StringIO()
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
But this doesn't work. Fails with:
File "./test.py", line 17, in <module>
subprocess.call(["somecommand", "someparam"], stdout=stdout_file, stderr=stderr_file)
File "/usr/lib/python2.7/subprocess.py", line 493, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.7/subprocess.py", line 672, in __init__
errread, errwrite) = self._get_handles(stdin, stdout, stderr)
File "/usr/lib/python2.7/subprocess.py", line 1063, in _get_handles
c2pwrite = stdout.fileno()
AttributeError: StringIO instance has no attribute 'fileno'
I see that it's missing some parts of the native file object and fails because of that.
So the question is more educational than practical - why these parts of file interface are missing from StringIO and are there any reasons why this cannot be implemented?