Connect with us

Hi, what are you looking for?

Latest

How do I run the Shell Command from Python and get the Output?

In Python it is often necessary to execute a Linux command and get the result of the command as a string variable. There are several ways to execute a shell command and get the result with Python. The naive way to do this is to execute the Linux command, save the result in a file and analyze the file.

1

2

3

Introduced in the OJ

cmd = ‘wc -l my_text_file.txt > from_file.txt’.

os.system(cmd)

Retrieving the command line output of subprocess

The best way to get the result of executing the Linux command in Python is to use the Python module subprocess. Here is an example of using a sub-process to calculate the number of lines in a file using the linux wc -l command

We start importing the subprocess module

Run the shell command we want to execute with the subprocess.popen function. The arguments for this command are the shell command in list form and the output and error specification.

1

2

3

>out = popen([‘toilet’, ‘-l’, ‘my_text_file.txt’] subprocess,

stdout=sub-process.PIPE,

stderr=sub-process.STDOUT)

The output of subprocess.popup is subprocess.popup. And this object gets the number of methods, and we will use the communication() method to get the default output and the error if it is a tuple.

Here the default output contains the result of the wc -l command, and in stderr – None, because there are no errors.

1

2

3

4

5

>stdout,stderr = out.communicate()

>print(stdout)

3503 my_text_file.txt

>print(stderr)

No, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no, no. No, no, no, no, no, no, no, no, no.

We can then parse the result of the command in Python as desired. For example, if we only want the number of lines in a file, we divide stdout

 

 

 python shell command output to variable,python run command line

You May Also Like