1

My pythonscript looks like this

#!/usr/bin/python3
#File Name: pythonScript.py
from sys import exit
if '__name__'=='__main__':exit(402)

And this is the shell script

python3 pythonScript.py
echo $?

It prints 146. How does 402 get mapped to 146? Some other pairs such as this are (402, 146), (100,0), (0, 0), (56, 0) etc.

Can the python script return value to shell this way, and is the ? the correct variable to capture this?

My machine version is this, if this is important.

4.4.0-89-generic #112-Ubuntu SMP Mon Jul 31 19:38:41 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux
Della
  • 1,264
  • 2
  • 15
  • 32
  • 1
    Your question already has an answer in https://stackoverflow.com/questions/9426045/difference-between-exit0-and-exit1-in-python/9426115 , e.g. Any value outside the range 0..255 is treated modulo 256 (the exit status is stored in an 8-bit value). 402 % 256 = 146 – Appleman1234 Oct 31 '18 at 07:00
  • `python -c 'exit(100)'` produces 100 in `$?` for me as expected. The other "pairs" in your question don't seem to be correct (or I misunderstand what you are trying to say). – tripleee Oct 31 '18 at 07:06

2 Answers2

1

in bash, the exit code is visible only the lowermost 8 bits, low 8 bits of 402 is 146:

>>> 402 & 0b11111111
146
georgexsh
  • 15,984
  • 2
  • 37
  • 62
0

It's not the shell. The system call interface only accommodates an unsigned 8-bit number; so the maximum value which can be communicated is 255.

The same thing would happen if you wrote a C program whose int main() tried to return(402); and you called it from another C program with exec, without any shell.

tripleee
  • 175,061
  • 34
  • 275
  • 318