The Python Oracle

Running bash commands in Python: os vs subprocess?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Switch On Looping

--

Chapters
00:00 Running Bash Commands In Python: Os Vs Subprocess?
00:42 Accepted Answer Score 1
01:35 Thank you

--

Full question
https://stackoverflow.com/questions/3910...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #bash

#avk47



ACCEPTED ANSWER

Score 1


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.