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!