How To Execute Shell Command with Python
Python provides a lot of modules for different operating system related operations. Running external command or shell command is very popular Python developers. We can call Linux or Windows commands from python code or script and use output.
Import os Module
We can use
system() function inorder to run shell command in Linux and Windows operating systems.
system() is provided by
os Module. So we will load this module like below.
Run Command with system Function
os module we can use
system() function by providing the external command we want to run. In this example we will run
ls command which will list current working directory content.
Import subprocess Module
Another alternative for running external shell command is
subprocess module. This module provides process related functions. We will use
call() function but first we need to load
Run Command with call Function
We will use
call() function which will create a separate process and run provided command in this process. In this example we will create a process for
ls command. We should provide the exact path of the binary we want to call.
Provide Parameters To The Command
We may need to provide parameters to the command we will call. We will provide a list where this list includes command or binary we will call and parameters as list items. In this example we will call
ls for path
Save Command Output To A Variable
We may need to save the command output to a variable or a file. We will put the output variable named
olike below. We will use
read() function of