Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Running bash commands in Python: os vs subprocess? [duplicate]

Tags:

python

bash

I read this question in which the asker is having a specific problem with running bash in Python using code like this:

os.system(bashCommand)

The top two answers simply say: "use subprocess" (instead of os.system), and give a quick code example.

What is the proper way to run bash commands with Python and why? To me, it seems that os.system is a good option, being designed for this type of thing, and it is simply a fluke that the asker of the other question couldn't accomplish correct functionality with that package. But, is it "the true Pythonic way" to use subprocess? Or in other words, what is the difference between os.system and subprocess?

like image 815
Joe Hansen Avatar asked Mar 02 '26 14:03

Joe Hansen


1 Answers

Subprocess gives you much more control over what's going on.

For example, you can redirect output to pipe it to your program like that:

process = subprocess.Popen(['ls', '-a'], stdout=subprocess.PIPE)
out, err = process.communicate()

(Example from python getoutput() equivalent in subprocess)

If you used system() you'd have to do redirection of input, saving it to file and weird things like that.


In documentation for os.system (https://docs.python.org/2/library/os.html#os.system) it is said that:

The subprocess module provides more powerful facilities for spawning new processes and retrieving their results; using that module is preferable to using this function. See the Replacing Older Functions with the subprocess Module section in the subprocess documentation for some helpful recipes.

like image 62
Dmitry Torba Avatar answered Mar 04 '26 05:03

Dmitry Torba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!