简体   繁体   中英

if __name__ == '__main__' function call

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

Within a module file you can write if __name__ == "__main__" to get specific behaviour when calling that file directly, eg 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 " .

If I understood your question correctly you want to do something like this:

# In a file called test.py
import main
import sys

... code

if __name__ == "__main__":
    main.main(sys.argv)
    ... rest of your code

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM