0

I have a shell script TestNode.sh. This script has content like this:

port_up=$(python TestPorts.py)
python TestRPMs.py

Now, I want to capture the value returned by these scripts.

TestPorts.py

def CheckPorts():
    if PortWorking(8080):
        print "8080 working"
        return "8080"
    elif PortWorking(9090):
        print "9090 working"
        return "9090"

But as I checked the answers available, they are not working for me. The print is pushing the value in variable port_up, but I wanted that print should print on the console and the variable port_up should get the value from return statement. Is there a way to achieve this?

Note: I don't wish to use sys.exit(). Is it possible to achieve the same without this?

Aakash Goyal
  • 1,051
  • 4
  • 12
  • 44

2 Answers2

2

but I wanted that print should print on the console and the variable port_up should get the value from return statement.

Then don't capture the output. Instead do:

python TestPorts.py
port_up=$? # return value of the last statement
python TestRPMs.py

You could do:

def CheckPorts():
    if PortWorking(8080):
        sys.stderr.write("8080 working")
    print 8080

But then I am not very happy to print "output" to stderr either.

Alternatively, you could skip printing that "8080 working" message in python script and print it from the shell script.

def CheckPorts():
    if PortWorking(8080):
        return "8080"

and:

port_up=$(python TestPorts.py)
echo "$port_up working"
python TestRPMs.py
P.P
  • 117,907
  • 20
  • 175
  • 238
  • That just tells whether the script execution was successful or not. – Aakash Goyal May 13 '16 at 10:37
  • If you want to use the exit value (to get port num), I don't see another way (shorting of writing to a file or parsing the python script's output etc). – P.P May 13 '16 at 10:39
  • Hmm, then I have to redesign my solution. Thanks :) – Aakash Goyal May 13 '16 at 10:42
  • 2
    I have updated with some more suggestions. It's not too tricky to solve this. But it's upto you decide which one you prefer. – P.P May 13 '16 at 10:49
0

To return an exit code from a Python script you can use sys.exit(); exit() may also work. In the Bash (and similar) shell, the exit code of the previous command can be found in $?.

However, the Linux shell exit codes are 8 bit unsigned integers, i.e. in the range 0-255, as mentioned in this answer. So your strategy isn't going to work.

Perhaps you can print "8080 working" to stderr or a logfile and print "8080" to stdout so you can capture it with $().

Community
  • 1
  • 1
PM 2Ring
  • 54,345
  • 6
  • 82
  • 182