Understand the Difference Between Python os.popen() and os.system(): A Completed Guide

By | April 30, 2020

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.

python call exe

Preliminary

Supposed cmd is a command line, which will be called by python script.

os.system(cmd)

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.

For example:

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.

os.popen(cmd)

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:

python os.popen() example

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.

Python Call .Exe File with Arguments – Python Tutorial

If there are some blank characters in cmd, to fix it, you can read:

Best Practice to Execute an EXE via os.popen() with White Spaces in the Path

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
os.popen() os._wrap_close Yes Yes

Leave a Reply

Your email address will not be published. Required fields are marked *