And this is one of the most useful things to do when you write a script. Using os.system() we cannot store the output of the Linux command into a variable. Later on in this article we will make a comparison between os.system and a different Python module called subprocess. I have written another article that explains Bash exit codes if it’s something you would like to know more about. Notice how the exit status is different from the one returned by the Bash shell: $ daet Let’s confirm that, by introducing a spelling mistake in the date command: > os.system('daet') That’s the exit code of the Linux command.Ī successful command in Linux returns a 0 exit code and a non-zero exit code is returned in case of failure. We still see the output of the date command but we also see a 0 in the last line. Let’s see what happens when we run the same code in the Python shell: > import os This is the output of the os.system() function: $ python shell_command.py It uses the system function of the os module to run the Linux date command: import os I have created a simple Python script called shell_command.py. Let’s start coding! Using OS System to Run a Command in Python
#Python subprocess get output line by line how to#
This will give you a full understanding of how to handle shell commands in Python. We will start this tutorial with the os module and then we will move to the subprocess module. The recommended module to run shell commands is the Python subprocess module due to its flexibility in giving you access to standard output, standard error and command piping. The simplest ones use the os.system and os.popen functions. There are multiple ways to execute a shell command in Python. Knowing how to execute a shell command in Python helps you create programs to automate tasks on your system.