-1

Say I have some python script that looks something like

# myscript.py
#!bin/env python

def func(argv):
    <some debugging print messages>
    <some logic>
    return some_string

def main():
    return func(sys.argv)

How can I capture the returned string value of this script in a bash script or terminal session (to print to console or use as value in another command)?

Have seen several other similar posts on SO (return value from python script to shell script, store return value of a Python script in a bash script), but these don't appear to account for the fact of needing the intermediate messages to remain in the code (eg. something like

#echo "$(myscript.py 'input')" 

ends up including all of the python script's debug messages along with the return value). Does anyone know what could be done here?

lampShadesDrifter
  • 3,925
  • 8
  • 40
  • 102
  • Do you want to capture this output in a file? –  Jun 14 '18 at 22:57
  • The script itself cannot return anything other than a single integer called the exit status. There is nothing special about your `main` function; it's return value is not treated specially by the script as a whole. – chepner Jun 14 '18 at 23:36

2 Answers2

4

If the return value (which is unclear in the question) is a single line of output you could simply:

./script.py | tail -n 1

This will output the last line generated from the script (adjust the number as needed).

If you want to save to a file either > to create a new file, or >> to append to a file:

./script.py | tail -n 1 > file 
l'L'l
  • 44,951
  • 10
  • 95
  • 146
  • This is the answer that I ended up using. For others finding this post, but with slightly different situations, some other ways to return values from python scripts can be found here: https://stackoverflow.com/a/18231470/8236733. – lampShadesDrifter Jun 15 '18 at 00:31
  • Yes, you can use `sys.exit(123)` in python. Then shell will intercept exit code in `echo $?` – Calvin Kim Jun 15 '18 at 01:48
-1

Instead of printing, use the logging module. It will print to stderr by default and you can redirect that somewhere else... OR disable all debugging output. Take a look at the table at the top of this page for usage advice: https://docs.python.org/2/howto/logging.html

Josep Valls
  • 5,483
  • 2
  • 33
  • 67