Gromit
Gromit

Reputation: 121

Python function returns different values when executed from a Bash script

I have a sample Python file "Test_exit.py":

import os

def test_exit():
    print('Line 1.\n')
    print('Line 2.\n')
    exit (17)

if __name__ == '__main__':
    test_exit()

When I execute it using Python, it works as expected:

ubuntu@ip-172-31-9-235:~$ python3 Test_exit.py
Line 1.

Line 2.

When I check the returned error code, it does print "17" as expected:

ubuntu@ip-172-31-9-235:~$ echo $?
17

However, things work different when I execute the same Python file from a Bash script "Test_exit.sh":

#!/bin/bash

    Exit_code=$(python3 Test_exit.py)
    echo $Exit_code 

I would expect it to echo "17", but it doesn't:

ubuntu@ip-172-31-9-235:~$ ./Test_exit.sh
Line 1. Line 2.

Not only it doesn't echo "17", but now the two lines are printed without a new line...

If I replace exit (17) with sys.exit (17), then nothing is printed, not even the 2 lines in a single line...

What's wrong with my code? Does exit cause not only Python to exist, but Bash script as well? And why are strings printed differently depending on how Python is called?

EDIT

For future reference, here is the script that works well, as advised by @choroba:

#!/bin/bash

    output=$(python3 Test_exit.py)
    Exit_code=$?
    echo "$Exit_code"
    echo "$output"

Upvotes: 1

Views: 106

Answers (1)

choroba
choroba

Reputation: 241988

The command substitution $(...) doesn't return the exit code, it captures the output. Use $? to check the exit code.

output=$(python3 Test_exit.py)
exit_code=$?

To get the exact output, you need to double quote the variable:

echo "$Exit_code"

Without quotes, the variable is expanded and undergoes word-splitting, so each word in the output is treated as a separate argument to echo which leads to reduction of whitespace to single spaces.

Upvotes: 6

Related Questions