Raising exception on STDIN read
iclark at mail.ewu.edu
Thu Feb 28 18:22:21 CET 2008
On 2008-02-28, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote:
> En Thu, 28 Feb 2008 14:29:04 -0200, Ian Clark <iclark at mail.ewu.edu>
>> On 2008-02-27, Gabriel Genellina <gagsl-py2 at yahoo.com.ar> wrote:
>>> En Wed, 27 Feb 2008 15:06:36 -0200, Ian Clark <iclark at mail.ewu.edu>
>>>> On 2008-02-27, Michael Goerz <newsgroup898sfie at 8439.e4ward.com> wrote:
>>>>> I would like to raise an exception any time a subprocess tries to read
>>>>> from STDIN:
>>>>> latexprocess = subprocess.Popen( \
>>>>> 'pdflatex' + " " \
>>>>> + 'test' + " 2>&1", \
>>>>> shell=True, \
>>>>> cwd=os.getcwd(), \
>>>>> env=os.environ, \
>>>>> stdin=StdinCatcher() # any ideas here?
>>>>> An exception should be raised whenever the pdflatex process
>>>>> reads from STDIN... and I have no idea how to do it. Any suggestions?
>>>> How about with a file-like object? I haven't tested this with
>>>> so you might want to read the manual on files if it doesn't work.
>>> Won't work for an external process, as pdflatex (and the OS) knows
>>> about Python objects. The arguments to subprocess.Popen must be actual
>>> files having real OS file descriptors.
>> Taken from the subprocess documentation (emphasis mine). 
>> stdin, stdout and stderr specify the executed programs' standard
>> input, standard output and standard error file handles,
>> respectively. Valid values are PIPE, an existing file descriptor (a
>> positive integer), *an existing file object*, and None.
>> The following peice of code works fine for me with the subprocess
>> module. NOTE: the only difference from this and the last I posted is
>> that I set fileno() to _error().
>> import sys
>> import subprocess
>> class ErrorFile(object):
>> def _error(self, *args, **kwargs):
>> raise AssertionError("Illegal Access")
>> def _noop(self, *args, **kwargs):
>> close = flush = seek = tell = _noop
>> next = read = readline = readlines = xreadlines = tuncate =
>> truncate = write = writelines = fileno = _error
>> # ^^^^^^
>> proc = subprocess.Popen("cat -", shell=True, stdin=ErrorFile())
>> ret = proc.wait()
>> print "return", ret
> I don't see how this could ever work. The shell knows nothing about your
> ErrorFile objects. If subprocess.Popen doesn't reject that ErrorFile
> instance, it's a bug. An ErrorFile instance is not "an existing file
Could you please explain why this won't work. ErrorFile exposes most all
attributes of file objects, so I don't understand why it wouldn't be
considered a file object.
Did you try running the code by any chance? It works fine for me on
2.5.1 on Linux.
More information about the Python-list