retro.dad
retro.dad

Reputation: 125

Can you return a value from a main() function in Python?

Let's say I have a utility script:

utility.py

def func1(input):
    # do stuff to input
    return stuff

def func2(input):
    # do more stuff to input
    return more_stuff

def main(argv):
    stuff = func1(argv[1])
    more_stuff = func2(argv[1])
    all_stuff = stuff + more_stuff
    # write all_stuff to stdout or file

if __name__ == "__main__":
    main(argv)

And this script is called by another rollup script, like so:

rollup.py

import utility

def main(argv):
    # assuming a list of of inputs is in argv[1]
    inputs = argv[1]
    for input in inputs:
        utility.main(['utility.py', input])

if __name__ == "__main__":
    main(argv)

Now let's say I want the rollup script to print or write to file a combined output of all the stuff generated by each instance of utility.py.

Is there any way to do this by returning the output from utility.py to the rollup script? Or does the rollup script have to read in all the output or output files that utility.py generated?

Note that I am not asking if this is considered best practices or if it's "allowed" in programming circles. I am aware that main is supposed to only return success or fail codes. I'm merely asking if it is possible.

Upvotes: 10

Views: 33165

Answers (2)

Daniele Murer
Daniele Murer

Reputation: 247

It is possible. You could, for instance, return a dictionary (or list, or tuple, or whatever) in utility.main() and then grub all the dictionaries and store them in a list in rollup.main(), inside the for loop, for further elaboration.

Your utility.main() is nothing else than a normal function in this case.

Upvotes: 0

Fred
Fred

Reputation: 1492

In your code the main function is nothing more than a regular function named main. So if you're asking if you can use return in your main function, then absolutely yes. You most certainly can

Upvotes: 8

Related Questions