How To Execute Shell Command with Python

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/execute-shell-command-python/
PINTEREST
PINTEREST
INSTAGRAM

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

After loading 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.

Run Command with system Function

Run Command with system Function

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 subprocess module.

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.

Run Command with call Function

Run Command with call Function

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 /etc/ with -l parameter.

LEARN MORE  Python Subprocess and Popen with Examples

Provide Parameters To The Command

Provide Parameters To The Command

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 popen()returned object.

Save Command Output To A Variable

Save Command Output To A Variable

RSS
EMAIL
FACEBOOK
FACEBOOK
GOOGLE
GOOGLE
https://www.poftut.com/execute-shell-command-python/
PINTEREST
PINTEREST
INSTAGRAM

You may also like...

Leave a Reply

Your email address will not be published.

Enjoy this blog? Please spread the word :)