Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

if __name__ == '__main__' function call

Tags:

python

I am trying to work around a problem I have encountered in a piece of code I need to build on. I have a python module that I need to be able to import and pass arguments that will then be parsed by the main module. What I have been given looks like this:

#main.py
if __name__ == '__main__' 
    sys.argv[] #pass arguments if given and whatnot
    Do stuff...

What I need is to add a main() function that can take argument(s) and parse them and then pass them on like so:

#main.py with def main()
def main(args):
    #parse args
    return args

if __name__ == '__main__':
    sys.argv[] #pass arguments if given and whatnot
    main(sys.argv)
    Do stuff...

To sum up: I need to import main.py and pass in arguments that are parsed by the main() function and then give the returned information to the if __name_ == '__main_' part.

EDIT To clarify what I am doing

#hello_main.py 
import main.py

print(main.main("Hello, main"))

ALSO I want to still be able to call main.py from shell via

$: python main.py "Hello, main"

Thus preserving the name == main

Is what I am asking even possible? I have been spending the better part of today researching this issue because I would like to, if at all possible, preserve the main.py module that I have been given.

Thanks,

dmg

like image 854
DmgCtrl-b.net Avatar asked Jan 05 '23 14:01

DmgCtrl-b.net


1 Answers

Within a module file you can write if __name__ == "__main__" to get specific behaviour when calling that file directly, e.g. via shell:

#mymodule.py
import sys
def func(args):
    return 2*args

#This only happens when mymodule.py is called directly:
if __name__ == "__main__":
    double_args = func(sys.argv)
    print("In mymodule:",double_args)

One can then still use the function when importing to another file:

#test.py
import mymodule
print("In test:",mymodule.func("test "))

Thus, calling python test.py will result in "In test: test test ", while calling python mymodule.py hello will result in "In mymodule: hello hello ".

like image 176
M.T Avatar answered Jan 15 '23 04:01

M.T