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?

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

4 Comments

That just tells whether the script execution was successful or not.
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).
Hmm, then I have to redesign my solution. Thanks :)
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.
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 $().

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.