How to know if python script was run using interpreter's -m option?

后端 未结 2 968
陌清茗
陌清茗 2021-01-02 13:48

I couldn\'t find answer after having read all the following:

  • PEP 338 Executing modules as scripts
  • documentation of runpy standard modul
相关标签:
2条回答
  • 2021-01-02 14:09

    Another observation is that __package__ is set to None when executing the script directly and to the package name when using -m (using the empty string when the module isn't included in any package, so it's still different from None).

    0 讨论(0)
  • 2021-01-02 14:14

    Disclaimer: this is just an observation, I have not seen it in the docs so it is probably implementation dependent and might not be consistent across different Python versions.

    I have noticed that when calling a script using a -m option a variable called __loader__ is added to the namespace, so at the top of your script you could check for existence of that variable:

    if '__loader__' in globals():
        # called with -m
    

    For some extra safety you could check to see if __loader__ is an instance of pkgutil.ImpLoader:

    if '__loader__' in globals() and __loader__.__class__.__name__ == 'ImpLoader':
    
    0 讨论(0)
提交回复
热议问题