Raising exception on STDIN read

Ian Clark iclark at mail.ewu.edu
Thu Feb 28 17:29:04 CET 2008


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>  
> escribi�:
>
>> On 2008-02-27, Michael Goerz <newsgroup898sfie at 8439.e4ward.com> wrote:
>>> Hi,
>>>
>>> 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 subprocess
>> so you might want to read the manual on files if it doesn't work[1].
>
> Won't work for an external process, as pdflatex (and the OS) knows nothing  
> about Python objects. The arguments to subprocess.Popen must be actual  
> files having real OS file descriptors.

Taken from the subprocess documentation (emphasis mine). [1]

	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):
            pass

        close = flush = seek = tell = _noop
        next = read = readline = readlines = xreadlines = tuncate = _error
        truncate = write = writelines = fileno = _error
        #                               ^^^^^^

    proc = subprocess.Popen("cat -", shell=True, stdin=ErrorFile())
    ret = proc.wait()
    print "return", ret

Ian

[1] http://docs.python.org/lib/node528.html




More information about the Python-list mailing list