python os.popen() and os.system() can allow python script to call other applications, however, there some differences between them. In this tutorial, we will discuss these differences.
Supposed cmd is a command line, which will be called by python script.
It will block the main process, if cmd is run successfully, it will reutn 0, otherwise, it return 1. We can not get the output of cmd.
import os cmd = 'conda' result = os.system(cmd) print(result)
Run this code, you will get the result 1, which means we can not run command line: conda.
Moreover, we can not get the error message.
It also can block the main process, meanwhile, it can return the output of cmd.
Here is an example:
import os cmd = 'ping www.tutorialexample.com' print("--start--") result = os.popen(cmd) print(type(result)) print(result.read()) print("--end--")
Run this code, you will find this result:
From the result, we can find os.popen() return a os._wrap_close object, we can read the output of cmd by it.
os.popen() will block the main python process, which means the python script will continue to run after the cmd finished.
If you plan to run cmd with some arguments, here is the tutorial.
If there are some blank characters in cmd, to fix it, you can read:
To summary, the difference between os.system() and os.popen() is:
|Return||Block main process||Get cmd ouput|
|os.system()||1 or 0||Yes||No|