Dan Cook
Dan Cook

Reputation: 2072

Why does bash echo print 0 for a Python function that exits 1

With a Python function in testreturn.py defined as:

import sys
def main():
    sys.exit(1)

When called from a bash function in scrip.sh defined as:

#!/bin/bash
function test()
{  
   python testreturn.py
   echo $?
}

Why does the following command:

test

Print

0

I would like the bash function to print the exit code of the python script.

Upvotes: 3

Views: 85

Answers (2)

bitsplit
bitsplit

Reputation: 1060

Because python will not call main by default. You have to call it explicitly.

You want:

import sys
def main():
    sys.exit(1)

if __name__ == "__main__":
    main()

Upvotes: 4

nosklo
nosklo

Reputation: 223062

Because you're defining, but never calling the main() function. The code finishes as normal (by reaching the end of the file) and return code is 0 in this case.

Upvotes: 5

Related Questions