Page 1 of 1

Run external command and get output

Posted: Mon Dec 03, 2018 5:50 pm
by Killertechno
Hi to all, I am a noob in python and I need to run shell scripts.

I've found some examples:

Code: Select all

import subprocess, sys

cmd = "sudo /etc/init.d/ntp stop"
p = subprocess.Popen(cmd, shell=True, stderr=subprocess.PIPE)

## Talk with date command i.e. read data from stdout and stderr. Store this info in tuple ##
## Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached.  ##
## Wait for process to terminate. The optional input argument should be a string to be sent to the child process, ##
## or None, if no data should be sent to the child.
(output, err) = p.communicate()

## Wait for date to terminate. Get return returncode ##
p_status = p.wait()
print "Command output : ", output
print "Command exit status/return code : ", p_status

Output is:
[email protected]:~/mypython/command $ python
[ ok ] Stopping ntp (via systemctl): ntp.service.
Command output : None
Command exit status/return code : 0

So I have no string containing command output.
If I try to run wrong command, I correctly get -1 as return code value.

If I try this:

Code: Select all

from subprocess import check_output

CommandOutput=check_output(["sudo", "ntpdate", ""])
print ("Result:")
print (CommandOutput)
I correctly get output command on CommandOutput string, but if my command is not correct, I got following result:

3 Dec 17:48:58 ntpdate[6989]: no server suitable for synchronization found
Traceback (most recent call last):
File "", line 49, in <module>
out=check_output(["sudo", "ntpdate", ""])
File "/usr/lib/python2.7/", line 219, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['sudo', 'ntpdate',']' returned non-zero exit status 1

So, how can I join two behaviours and get both output string and manage output code?

Re: Run external command and get output

Posted: Mon Dec 03, 2018 11:02 pm
by Andyroo
You could wrap your command around a ‘try’ and handle errors within that.

For example, to check if a device is up before pulling data from it, I have a simple ping command:

Code: Select all

# Returns TRUE if site responds to ping else returns FALSE

def ping(site):
    cmd = "/bin/ping -c 1 -W 1 " + site
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)"Ping to %s worked fine", site)
        return True
        logging.error("Ping to %s failed", site)
        return False
In my case I’m just returning a Boolean to say if I could contact the device but you could pass the output back or even turn the output variable to a global.