-3

I have a python script that both prints and returns some value. Like:

(pseudo code)
def main:
    print "hello"
    return 1

I'd like the shell script to capture the value returned (1) not the value printed (hello).

instant501
  • 195
  • 1
  • 10
  • 1
    `main` is not in anyway specific. The name is not reserved any purpose. You have to show how you invoke your function `main` from your main program. – user1934428 Jun 01 '23 at 14:57

2 Answers2

3

Returning a value from that main() function doesn't do anything here.

To return an exit code to the operating system (and thus a shell script), you should use sys.exit().

declension
  • 4,110
  • 22
  • 25
  • 1
    Worth noting that sys.exit() cannot be used to return arbitrary values as it's limited to integers that can be expressed in 8 bits. e.g., sys.exit(300) will return 44 to the shell – DarkKnight Jun 01 '23 at 08:23
  • @DarkKnight : AFIK, values larger than 127 are technically possible, but discouraged too - at least in Unix-like operating system -, because values with the high-bit set usually are used by OS to signal problems when starting a process. – user1934428 Jun 01 '23 at 14:53
1

The script need to utilise sys.exit() in order to pass back some value to the caller. The value that can be return is limited to integers that can be expressed in 8 bits

For example we have foo.py implemented as:

import sys

print('All the world\'s a stage, And all the men and women merely players')
sys.exit(99)

Then, in another .py file we can have:

from subprocess import run

print(run(['python3', 'foo.py'], capture_output=True).returncode)

Output:

99
DarkKnight
  • 19,739
  • 3
  • 6
  • 22