Killertechno
Posts: 190
Joined: Wed Jan 02, 2013 8:28 am

Run external command and get output

Mon Dec 03, 2018 5:50 pm

Hi to all, I am a noob in python and I need to run shell scripts.

I've found some examples:

Code: Select all

#!/usr/bin/python
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 command.py
[ 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", "7.3.4.2"])
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 "command.py", line 49, in <module>
out=check_output(["sudo", "ntpdate", "7.3.4.5"])
File "/usr/lib/python2.7/subprocess.py", line 219, in check_output
raise CalledProcessError(retcode, cmd, output=output)
subprocess.CalledProcessError: Command '['sudo', 'ntpdate', 7.3.4.5']' returned non-zero exit status 1

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

Andyroo

Re: Run external command and get output

Mon Dec 03, 2018 11:02 pm

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
    try:
        output = subprocess.check_output(cmd, stderr=subprocess.STDOUT, shell=True)
        logging.info("Ping to %s worked fine", site)
        return True
    except:
        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.

Return to “Python”