Python Friday #98: Run Other Applications From Your Code

Python allows us to run other applications from our code. That helps us to reuse existing tools as part of our automation. Let’s look how we can do that.

This post is part of my journey to learn Python. You can find the other parts of this series here. You find the code for this post in my PythonFriday repository on GitHub.

 

Run another application

You can run another application with the built-in Python module subprocess. You need to put the name of the application (and the parameters) as the first argument of the run() method:

Instead of one long string with all arguments you can use a list:

When you run the code, it starts Git and runs the shortlog command. Your code waits until Git finishes before Python continues with your code.

 

Capture the output

The code snipped above mixes the output of git shortlog with your application. This may be a problem. However, you can tell the run() method to capture your output as text and assign it to a variable. This is similar to the output capturing of pytest:

When we run this code, we capture the standard output in the field stdout and the errors go to stderr:

stdout: Johnny Graber (52):
Initial commit
Update README.md
add examples for logging in Python
Create log2seq.py

stderr:
***

 

Conclusion

The subprocess module offers us great flexibility to run different applications inside our Python code. That allows us to leverage existing tools without writing everything from scratch.

1 thought on “Python Friday #98: Run Other Applications From Your Code”

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.