Running bash commands in Python: os vs subprocess?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Track title: CC I Beethoven Sonata No 31 in A Flat M
--
Chapters
00:00 Question
00:54 Accepted answer (Score 1)
01:53 Thank you
--
Full question
https://stackoverflow.com/questions/3910...
Question links:
[this question]: https://stackoverflow.com/q/4256107/7563...
Accepted answer links:
[python getoutput() equivalent in subprocess]: https://stackoverflow.com/questions/6657...
https://docs.python.org/2/library/os.htm...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #bash
#avk47
--
Track title: CC I Beethoven Sonata No 31 in A Flat M
--
Chapters
00:00 Question
00:54 Accepted answer (Score 1)
01:53 Thank you
--
Full question
https://stackoverflow.com/questions/3910...
Question links:
[this question]: https://stackoverflow.com/q/4256107/7563...
Accepted answer links:
[python getoutput() equivalent in subprocess]: https://stackoverflow.com/questions/6657...
https://docs.python.org/2/library/os.htm...
--
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.