Home > python > Execute command, show its output, get its exit code

Execute command, show its output, get its exit code

Problem
You want to execute an external program, show its output, and get its exit code at the end.

Solution

import shlex
from subprocess import Popen, PIPE

cmd = "..."
process = Popen(shlex.split(cmd), stdout=PIPE)
process.communicate()    # execute it, the output goes to the stdout
exit_code = process.wait()    # when finished, get the exit code

Example: I used this code with FFmpeg. FFmpeg updates the output on the stdout regularly while doing a conversion. At the end I can ask if the conversion was successful (exit_code == 0) or not.

Advertisements
Categories: python Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: