[Tutor] subprocess.Popen()

Mats Wichmann mats at wichmann.us
Mon Dec 3 11:27:26 EST 2018


On 12/2/18 3:29 AM, Dave Hill wrote:

> Having 'graduated' to Python 3.7, I thought I would explore
> subprocess.Popen, and put the code in a Class, see code below. The video
> runs, but an error occurs, which I do not understand, see further below

the error happens in the except clause of your try block ...

> Traceback (most recent call last):
...
>   File "/home/pi/Code/VideoPlayer.py", line 51, in playVideo
>     out = omxp.communicate()
...
>   File "/usr/lib/python3.5/selectors.py", line 39, in _fileobj_to_fd
>     "{!r}".format(fileobj)) from None
> ValueError: Invalid file object: <_io.BufferedReader name=8>

You can see that the call to communicate() is the one without arguments,
so it's in your cleanup code.   You should catch the specific exception
you expect could happen here, which is probably a timeout - but you
can't tell because you don't specify it.

>         try:
>             out = omxp.communicate(timeout=self.timeout)
>             print("Try outs =  ", StringIO(out))
>         except:
>             omxp.kill()
>             out = omxp.communicate()
>             print("Except outs =  ", StringIO(out))

use

      except TimeoutExpired:

then it looks like the file descriptor for the second communicate is no
longer valid... here's a larger chunk from subprocess that shows what it
is raising and how it got there:

    if isinstance(fileobj, int):
        fd = fileobj
    else:
        try:
            fd = int(fileobj.fileno())
        except (AttributeError, TypeError, ValueError):
            raise ValueError("Invalid file object: "
                             "{!r}".format(fileobj)) from None


In other words, it's raising the ValueError you see  because it's not a
file object. The "from None" part suppresses the context from the
original exception.

Note that communicate returns a tuple so your 'out' is actually a tuple,
and this is likely what is going wrong - by calling StringIO(out) in the
try: you are causing an exception which isn't the exception one would
expect; by not being explicit in your except: you catch that error and
take cleanup steps that are not appropriate - your video probably
finished normally.

hopefully this will help debug things...



More information about the Tutor mailing list