0

I'm relatively new in shell scripting and I wanted to have some clarification on the following.

If i have a python script that does the following:

def return_output():
    a = 1
    b = 2
    return a+b

if __name__ == "__main__":
    return_output()

and say I want to run this script in bash in which I would want to retrieve the output value in bash via a variable:

summation=$(python total.py)
echo $summation

If i run the following shell script, nothing will be echoed.

However, i notice that when i change the python code of "return a+b" to "print(a+b)" instead, I would get the echoed value of "3" when i run the shell script.

3

Therefore my question is, if a python script were to be made to execute in a terminal, does it always have to print the output instead of using the return keyword?

Maxxx
  • 3,688
  • 6
  • 28
  • 55

2 Answers2

1

Yes. Bash has no (simple) way to communicate with Python other than Python's stdout, so you will always have to print the output if you want bash to know what that output is.

Seth
  • 2,214
  • 1
  • 7
  • 21
1

Yes.

You'll want to print(...) (write to stdout) to capture the output of the script in a variable.

You can, in addition to that, call sys.exit(0), when the script ran successfully or, call sys.exit(1) if the script fails. This adheres to common UNIX CLI patterns.

Alex
  • 34,899
  • 5
  • 77
  • 90