ThePopMachine
ThePopMachine

Reputation: 142

How to determine from within whether a Python module/file was imported or invoked standalone?

I would like to structure some Python code such that I can either invoke it from the command line, or import it as a package from another program.

If I import it, I will invoke it, say, through its main() function with some parameters. If it's executed directly, I will call main() with default parameters at the end of the file.

How, from inside the module, do I determine whether to call main() with default parameters or not?

Alternatively, when I call imp.importlib.import_module() is there a way to pass options into the module (say through its globals) ?

Upvotes: 0

Views: 82

Answers (1)

ForceBru
ForceBru

Reputation: 44858

You can check if a file is run directly with:

if __name__ == '__main__':
    print("I am run as a script!")
else:
    print("I am being imported")

Upvotes: 2

Related Questions