[Python] if __name__ == '__main__' function call

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    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 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:

    #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...


    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 would like to, if at all possible, preserve the main.py module that I have been given.

    Continue reading...

Compartilhe esta Página