Python Conditional Statements Based on Success of Last Command

In shell scripting, I can create a conditional statement based on the success or failure (exit status)of a command such as:

pinger()
{
ping -c 2 $remote_host >/dev/null 2>&1
ping_stat=$?
}

pinger 
if [[ $ping_stat -eq 0 ]]; then

	echo "blahblahblah" 
  exit 0
fi

how is this done using Python using exit status?

The return value of os.system("shell command"); is the return code of whatever was ran. You'd check for success by checking if it was zero.

1 Like

Be aware!

Last login: Thu Oct 24 23:06:01 on ttys000
AMIGA:barrywalker~> python3.3
Python 3.3.2 (v3.3.2:d047928ae3f6, May 13 2013, 13:52:24) 
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import os
>>> retcode=os.system("claer")
sh: claer: command not found
>>> type(retcode)
<class 'int'>
>>> print(retcode)
32512
>>> retcode=os.system("ls /tmp")
0001d5269d380		launch-Tz0C4e		launchd-1575.z2293S
launch-KKNp3U		launch-hwShRg		text
launch-MSWbKw		launchd-124.mdpfPn
>>> type(retcode)
<class 'int'>
>>> print(retcode)
0
>>> _
1 Like

Hi, wisecracker.

From the python os.system documentation:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). 

You should read the man page for the wait(2) system call. The integer returned, (32512 above) encodes more information than just the value passed to the exit system call. There are macros that are used to extract the actual value passed to exit(). Python's os module provides access to those macros. The two most relevant to your post:

os.WIFEXITED(status)

    Return True if the process exited using the exit(2) system call, otherwise return False.

    Availability: Unix.

os.WEXITSTATUS(status)

    If WIFEXITED(status) is true, return the integer parameter to the exit(2) system call.
    Otherwise, the return value is meaningless.

    Availability: Unix.

Those excerpts are from Python Standard Library - 16.1 - os.

To summarize, you cannot directly read the integer returned by wait(2) (which is the return value of os.system on UNIX). Also, you should not use bit shifting and/or masking to extract the relevant status bits because the encoding is allowed to differ between system implementations.

Regards,
Alister

1 Like