如何知道 python 脚本是否使用解释器的 -m 选项运行?
阅读完以下所有内容后,我找不到答案:
基本原理:
当使用相对导入的测试脚本在没有 -m
选项的情况下运行时,我可以打印一条警告消息,而不是给用户留下标准回溯,导致 ValueError: Attemptedrelative import in non-package< /代码> 异常。在不知道这一点的情况下,我可以捕获此异常,并且只有 suggest 缺少
-m
选项可能是错误的原因。
I couldn't find answer after having read all the following:
- PEP 338 Executing modules as scripts
- documentation of
runpy
standard module - description of Python interpreter's
-m
option
Rationale:
When a test script which uses relative imports is being run without -m
option I could print a warning message instead of leaving user with standard traceback leading to ValueError: Attempted relative import in non-package
exception. Without knowing this I can catch this exception and only suggest lack of -m
option could be the reason of error.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
免责声明:这只是一个观察,我没有在文档中看到它,所以它可能依赖于实现,并且在不同的 Python 版本之间可能不一致。
我注意到,当使用
-m
选项调用脚本时,名为__loader__
的变量会添加到命名空间中,因此在脚本的顶部,您可以检查是否存在该变量:为了额外的安全性,您可以检查 __loader__ 是否是
pkgutil.ImpLoader
的实例: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:For some extra safety you could check to see if
__loader__
is an instance ofpkgutil.ImpLoader
:另一个观察结果是,直接执行脚本时,
__package__
设置为None
,使用-m
时设置为包名称(在执行时使用空字符串)该模块不包含在任何包中,因此它仍然与None
不同)。Another observation is that
__package__
is set toNone
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 fromNone
).