How to import a module as __main__?

There is, execute the script instead of importing it. But I consider this an extremely hackish solution.

However the ideal pattern would be:

def do_stuff():
    ... stuff happens ...

if __name__ == '__main__':
    do_stuff()

that way you can do:

from mymodule import do_stuff
do_stuff()

EDIT: Answer after clarification on not being able to edit the module code.

I would never recommend this in any production code, this is a "use at own risk" solution.

import mymodule

with open(os.path.splitext(mymodule.__file__)[0] + ".py") as fh:
    exec fh.read()

Put that code in a function, and call it from the module you are importing it into as well.

def stuff():
    ...

if __name__ == '__main__':
    stuff()

And then in the module you are importing it into:

import module
module.stuff()

As pointed out in the other answers, this is a bad idea, and you should solve the issue some other way.

Regardless, the way Python does it is like this:

import runpy
result = runpy._run_module_as_main("your.module.name"))

Tags:

Python