2

Using subprocess.Popen(), I'm launching a process that is supposed to take a long time. However, there is a chance that the process will fail shortly after it launches (producing a return code of 1). If that happens, I want to intercept the failure and present an explanatory message to the user. Is there a way to "listen" to the process and respond if it fails? I can't just use Popen.wait() because my python program has to keep running.

The hack I have in place right now is to time.sleep() my python program for .5 seconds (which should be enough time for the subprocess to to fail if it's going to do so). After the python program resumes, it polls the subprocess to determine if it has failed or not.

I imagine that a better solution might use threading and Popen.wait(), but I'm a relative beginner to python.

Edit: The subprocess is a Java daemon that I'm launching. If another instance of the daemon is already running on the system, the Java subprocess will exit with a return code of 1, and I want to intercept the messy Java exception stack trace and present an understandable error message to the user.

9
  • 1
    So you essentially want Popen.wait with a timeout? Commented Aug 8, 2012 at 19:57
  • Add some of your existing code Commented Aug 8, 2012 at 19:57
  • Is it possible to handle the failure inside the subprocess? If not, can you give more details about what you're doing? Commented Aug 8, 2012 at 20:01
  • See subprocess with timeout Commented Aug 8, 2012 at 21:24
  • A timeout would be helpful if the subprocess is supposed to return promptly but instead keeps running without returning anything. My situation is the other way around: the subprocess is supposed to keep running without returning anything, and I want to present an error message to the end user if it does return promptly (with a return code of 1). Is it possible to monitor stdout of the subprocess without stopping execution flow of my main python program? Commented Aug 9, 2012 at 22:44

1 Answer 1

1

Two approaches:

  • Call Popen.wait() on a thread as you suggested yourself, then call an error handler function if the exit code is non-zero. Make sure that the error handler is thread safe, preferably by dispatching the error message to the main thread if your application has an event loop.
  • Rewrite your application to use an event loop that already supports monitoring child processes, such as pyev. If you just want to monitor one subprocess, this is probably overkill.
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.