Python - execute external command and get output

By d-erf | Devtips | 20 Jun 2020


Hello python devs!

 

Question here is to practically execute and external command like a system command, and get the output in a variable to work with.

 

Do do such, use subprocess import:

 

#!/usr/bin/env python
import subprocess
import pprint
 

cmd = "cd /opt;ls -l"

p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)

(output, err) = p.communicate()
 
p_status = p.wait()

pprint(output)


exit()

 

Note the "shell=True" option:https://docs.python.org/3/library/subprocess.html

You can now work on the output itself.

Even if you are supposed to get json as output, you'll probably need to delete unwanted characters like "\n":

 

output = output.replace("\n", "")

  Or transform dict like ouput into real dict:   add import ast at the beginning of the file +   

dictresult = ast.literal_eval(output)

 

 

 

Hope it helps friends, see you!

How do you rate this article?

0



Devtips
Devtips

Dev tips and tricks

Send a $0.01 microtip in crypto to the author, and earn yourself as you read!

20% to author / 80% to me.
We pay the tips from our rewards pool.