How to run ubuntu command from Python Program?

Here i will show you how to run ubuntu command from python program and store the output in python variable.

In python, there is one module named “subprocess” that contains various methods to spawn new processes, connect to their input/output/error pipes, and obtain their return codes. This module has one method called “check_output

Syntax:

subprocess.check_output(args*stdin=Nonestderr=Noneshell=Falsecwd=Noneencoding=Noneerrors=Noneuniversal_newlines=Nonetimeout=Nonetext=None**other_popen_kwargs)

By default, this function will return the data as encoded bytes.

Example : Below is the python program to show the use of subprocess.check_output() method.

In this example, i am using “ping command“, ping command is used to check whether the server (domain name or host name or server ip or host ip) is reachable or not.

-c : it is used to set the count parameter in ping command. Here our count is set to 10. Here in this example i am pinging “www.google.com” to 10 times.

www.google.com : This is the host name (domain name) to which i am pinging. If i do not specify the count value, ping command will run continuously and i have to stop it forcefully.

Output :

shell=True : Setting the shell argument to a true value causes subprocess to spawn an intermediate shell process, and tell it to run the command.

2 thoughts on “How to run ubuntu command from Python Program?”

Leave a Comment

Your email address will not be published. Required fields are marked *