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. Advertisements

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. Mark Goldin

    Errors, errors, errors

    Mark Goldin, Jan 17, 2004, in forum: ASP .Net
    Replies:
    2
    Views:
    1,277
    Mark Goldin
    Jan 17, 2004
  2. Edward C. Jones
    Replies:
    1
    Views:
    1,162
    Peter Hansen
    Apr 2, 2005
  3. johnny
    Replies:
    4
    Views:
    1,196
    Fredrik Lundh
    Dec 15, 2006
  4. Replies:
    1
    Views:
    425
    Gabriel Genellina
    Sep 8, 2007
  5. Replies:
    0
    Views:
    388
  6. Replies:
    8
    Views:
    757
    Nicola Musatti
    Jun 6, 2008
  7. Hseu-Ming Chen
    Replies:
    1
    Views:
    1,232
    Chris Torek
    Jun 12, 2011
  8. Atherun
    Replies:
    18
    Views:
    4,123
    Atherun
    Sep 24, 2011
Loading...