Subprocess module - communicate(data) dealing with errors

Discussion in 'Python' started by Paul Moore, Nov 21, 2006.

  1. Paul Moore

    Paul Moore Guest

    I've just hit an annoying corner case in the subprocess module. I'm
    trying to run a process, pass it some input and capture output and
    error data:

    cmd = ['tr', 'a-z', 'A-Z']
    p = Popen(cmd, stdin=PIPE, stout=PIPE, stderr=PIPE)
    out, err = p.communicate("Hello, world!")

    This works really well, *except* if cmd has an error (for example, add
    an extra argument). In that case, the subprocess finishes before the
    communicate() call, and so the communicate() call fails with an
    IOError writing to the subprocess' stdin handle.

    The trouble is, as far as I can tell, this is a race condition - I can
    check (with poll()) if the command has terminated before I try
    communicate(), but there's still a chance it terminates between the
    poll and the communicate.

    I'd really like to make this as near to foolproof as I can - this is
    to go into a server process, and tracebacks aren't really suitable
    output... :) Can anyone suggest a way I can code defensively round
    this?

    In case it matters, I'm running on Windows - I don't know enough about
    POSIX to say if the same issue occurs there.

    Thanks for any suggestions,
    Paul.
    --
    Most conversations are simply monologues delivered in the presence of
    witnesses. -- Margaret Millar
     
    Paul Moore, Nov 21, 2006
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Edward C. Jones
    Replies:
    1
    Views:
    993
    Peter Hansen
    Apr 2, 2005
  2. johnny
    Replies:
    4
    Views:
    880
    Fredrik Lundh
    Dec 15, 2006
  3. Replies:
    1
    Views:
    380
    Gabriel Genellina
    Sep 8, 2007
  4. Replies:
    0
    Views:
    299
  5. Replies:
    8
    Views:
    543
    Nicola Musatti
    Jun 6, 2008
Loading...

Share This Page