-2

I have a Python script which is returning data by printing them, a function is not used.

I now want to make a function out of the script which works in the same way, but instead of printing the data, it should be returned by the app function.

Of course I could do it manually by writing "def myapp():", making all the indentations, and call it in the last line of the script, but I wonder if there is a tool for that?

scenox
  • 698
  • 7
  • 17
  • 1
    Step 1 : Write `def myapp():` at the top of your script | Step 2 : Highlight your entire script, and hit tab | Step 3 : `return` your result | You now have the ugliest function ever, I hope it works. Doubt an automatic tool could do much better. – miradulo May 17 '16 at 15:27
  • Possible duplicate of [Capture stdout from a script in Python](http://stackoverflow.com/questions/5136611/capture-stdout-from-a-script-in-python) – Matt S May 17 '16 at 15:30
  • 1
    When doing test-driven development, one is driven to write functions from the beginning so that test code can call the function and programmatically compare the actual result with the desired and expected result. To visually see the result, one writes, for instance, `print(f(arg))`. This separates *calculating* a result from *displaying* a result. – Terry Jan Reedy May 17 '16 at 15:51

1 Answers1

1

Always write your script as one or more functions ending in two "magic" lines. A suitable template is

import sys                # if you want a system return code
MY_CONSTANT = "whatever"  # a symbolic constant

def a_function( args):    # replace with your useful stuff
    pass

# def b_function( args):   # as many more defs as are useful
    # can refer to / use both a_function (above) and c_function (below)

# def c_function()
    # etc

def main():
    print( "Script starting ...")
    # parse arguments, if any parsing needed
    # do stuff using the functions defined above
    # print output, if needed
    print( "End of script")
    sys.exit(0)    # 0 is Linux success, or other value for $? on exit

# "magic" that executes script_main only if invoked as a script

if __name__ == "__main__": # are we being invoked directly from command line?
    main()                 # if so, run this file as a script. 

Why? This file (myfile.py) is also usable as an import, at the interpreter prompt or in another file / script / module. It will define the constants and functions but it will not actually run anything when being imported as below. Either

import myfile

so you can refer to myfile.a_function, myfile.MY_CONSTANT, etc. Or

from myfile import a_function  

and then you can invoke a_function(args) without needing the prefix. You'll often see test or some random name: main() is not special.

nigel222
  • 7,582
  • 1
  • 14
  • 22