Pkg generation script as __main__

Is there a way to make a package generated script behave the same as invoking via the module path ie get executed as __main__

The package generated script behaves like

python -c'from A.B.script import main;main()' abc

but this will get a different sys.path to invoking using

python -mA.B.script abc

even when script has

if __name__=='__main__':
    main()

In particular invoking via the module path sys.path starts with the current working directory

1 Like

You could have main() insert dirname(__file__) at the front of
sys.path ? But I’d want to know why you want this.

In an editor which is only used for scripts intended to be __main__ ie are normally run as
python <path>/startscript.py it seems reasonable that <path> should be on the python path.

I agree that the main method can ensure that the path is fixed, but I wondered if the run as __main__ mechanism used by python -mmodulepath is exposed somewhere for use in scripts?

If you’re looking for the implementation of the -m command line switch you probably want to look at the runpy module.

thanks, I have never used runpy as windows is not my preferred OS :slight_smile:

I think you’re confusing runpy with the py Windows Python launcher. Not the same thing at all; David included a link to the runpy stdlib module docs.

I think you are right, runpy does the run as __main__ trampoline. I’ve never used or known about it until now. I’ve installed python many times on windows and have always ignored the py thing.