Python System Command - os.system(),

In this tutorial we will learn about Python System Command. Previously we learned about Python Random Number.

Python System Command

While making a program in python, you may need to exeucte some shell commands for your program. For example, if you use Pycharm IDE, you may notice that there is option to share your project on github. And you probably know that file transferring is done by git, which is operated using command line. So, Pycharm executes some shell commands in background to do it.

However, In this tutorial we will learn some basics about executing shell commands from your python code.

Python os.system() function

We can execute system command by using os.system() function. According to the official document, it has been said that

This is implemented by calling the Standard C function system(), and has the same limitations.

However, if command generates any output, it is sent to the interpreter standard output stream. Using this command is not recommended. In the following code we will try to know the version of git using the system command git --version.

The following output found in ubuntu 16.04 where git is installed already.

Notice that we are not printing the git version command output to console, it’s being printed because console is the standard output stream here.

Python Function

In the previous section, we saw that os.system() function works fine. But it’s not recommended way to execute shell commands. We will use Python subprocess module to execute system commands.

We can run shell commands by using function. See the following code which is equivalent to the previous code.

And the output will be same also.

Python System Command

Python subprocess.check_output() function

So far, we executed the system commands with the help of python. But we could not manipulate the output produced by those commands. Using subprocess.check_output() function we can store the output in a variable.

It will produce output like the following

So, in the above sections we have discussed about basic ideas about executing python system command. But there is no limit in learning. If you wish, you can learn more about Python System command using subprocess module from official documentation.

By admin

Leave a Reply

%d bloggers like this: