Ubuntu – Return Value to Python script from shell

bashcommand linepythonscripts

I'm trying to return a string from shell script to python getting the below error.

./whiptail.sh: 10: return: Illegal number: uuiiu

i tried running the whiptail command within python directly using subprocess.Popen even at that point im not able to read the user input from python.. If anyone tried this please let me know how to solve this issue.

shell script snippet

#!/bin/sh


COLOR=$(whiptail --inputbox "What is your favorite Color?" 8 78 Blue --title "Example Dialog" 3>&1 1>&2 2>&3)
                                                                        # A trick to swap stdout and stderr.
# Again, you can pack this inside if, but it seems really long for some 80-col terminal users.
exitstatus=$?
if [ $exitstatus = 0 ]; then
    echo "User selected Ok and entered " $COLOR
    return $COLOR
else
    echo "User selected Cancel."
fi

echo "(Exit status was $exitstatus)"

Best Answer

Within sh which is actually dash on Ubuntu the builtin command return can returns only numerical values - exit statuses, which have a meaning in a context of a function or sourced script. Source man sh:

The syntax of the return command is

return [exitstatus]

Everything other with your shell script looks correct. I think you need to use echo $COLOR instead return and suppress other echo-es.

In case you need to return more data to the main script you can output everything as one line and divide the separate fields by some character that will play role of a delimiter in the main script on which base you can convert the string into an array. For example (where , is our delimiter and -n will suppers the newline character within echo):

echo -n "$COLOR","$exitstatus"

The other information that is provided by the script and is not required by the main script could be redirected to some log file:

$ cat whiptail.sh
#!/bin/sh
log_file='/tmp/my.log'

COLOR=$(whiptail --inputbox "What is your favorite Color?" 8 78 Blue --title "Example Dialog" 3>&1 1>&2 2>&3)
exitstatus=$?

if [ $exitstatus = 0 ]; then
    echo "User selected Ok and entered $COLOR" > "$log_file"
    echo -n "$COLOR","$exitstatus"
else
    echo "User selected Cancel."  >> "$log_file"
    echo -n "CANCEL","$exitstatus"
fi

Unfortunately I don't have much experience with Python, but here is a sample .py script that can handle the output of the above .sh script (reference):

$ cat main-script.py
#!/usr/bin/python
import subprocess

p = subprocess.Popen(['./whiptail.sh'], stdout=subprocess.PIPE)
p = p.communicate()[0]
p = p.split(",")
print "Color:    " + p[0]
print "ExitCode: " + p[1]