Thursday, November 10

Python calling shell commands

First of all, for this topic, we should always reference the official site of subprocess: https://docs.python.org/3.10/library/subprocess.html


Because when you do random google search, you will find some answers for this topic using os.system, Popen. You should know these answers are obsolete. The answers might be correct 10 years ago, but now, whenever possible, use the subprocess class to solve this problem. Of course if you are reading/using a 10-year-old program and trying to make sense of it ( you have my sympathy), then you can know the answer is still valid (but deprecated).


Second, I limit my scope in Linux shell only. Running python command in Windows is another topic that I don't have the capability to cover.


In one of my project, the code evolves itself into calling a lot of shell commands. At first it is calling ffmpeg to decode a video, then it is calling another python program to process , and it even calls "echo" to write timestamp and some information into a log file:


To keep the code simple, I was using `os.system()`.