How to get the current running module path/name

前端 未结 8 1967
不知归路
不知归路 2021-02-03 19:19

I\'ve searched and this seems to be a simple question without a simple answer.

I have the file a/b/c.py which would be called with python -m a.b.c

相关标签:
8条回答
  • 2021-02-03 20:20

    This works for me:

    __loader__.fullname
    

    Also if I do python -m b.c from a\ I get 'b.c' as expected.

    Not entirely sure what the __loader__ attribute is so let me know if this is no good.

    edit: It comes from PEP 302: http://www.python.org/dev/peps/pep-0302/

    Interesting snippets from the link:

    The load_module() method has a few responsibilities that it must fulfill before it runs any code:

    ...

    • It should add an __loader__ attribute to the module, set to the loader object. This is mostly for introspection, but can be used for importer-specific extras, for example getting data associated with an importer.

    So it looks like it should work fine in all cases.

    0 讨论(0)
  • 2021-02-03 20:23

    The only way is to do path manipulation with os.getcwd(), os.path, file and whatnot, as you mentioned.

    Actually, it could be a good patch to implement for optparse / argparse (which currently replace "%prog" in the usage string with os.path.basename(sys.argv[0]) -- you are using optparse, right? -- ), i.e. another special string like %module.

    0 讨论(0)
提交回复
热议问题