How to spawn a program and assign its stdout to a string variable?

Alex Martelli aleax at aleax.it
Sat Nov 9 09:44:53 EST 2002


Christopher R. Culver wrote:

> I'm working on a pdf2ps frontend script that will use the *nix utility
> "file" to determine a file's type without blindly trying to work on it. I
> assume the best way to do this is to spawn "file", capture its stdout to a
> string variable, and then use regular expressions to search within the
> captured stdout for the file type desired (in this case PDF). However,

Doubtful assumption, but, OK, it may be one way.

> I've tried these:
> 
> capturedstdout = os.system(["file"]+foo)
> 
> capturedstdout = swapvp('P_NOWAIT', 'file', ['file']+foo)
> 
> but these don't work because the return value of file is assigned to the
> variable "capturedstdout", not the stdout. How do I spawn a program and
> have its stdout assigned to a string variable?

>>> foo = 'ch01.xml.pdf'
>>> import os
>>> capturedstdout = os.popen('file ' + foo).read()
>>> print capturedstdout
ch01.xml.pdf: PDF document, version 1.3

>>>


Alex




More information about the Python-list mailing list