如何知道python脚本是否使用解释器的-m选项运行? [英] How to know if python script was run using interpreter's -m option?

查看:318
本文介绍了如何知道python脚本是否使用解释器的-m选项运行?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在读完所有以下内容后,我找不到答案:





原因:

当使用相对导入的测试脚本运行时没有 -m 选项时,我可以打印警告消息,而不是让用户使用标准追溯导致 ValueError:尝试相对导入非package 异常。不知道这个我可以抓住这个异常,只有建议缺少 -m 选项可能是错误的原因。

$ b $另一个观察结果是 __ package __ 设置为当使用 -m (当模块不包括在任何包中时使用空字符串,所以它仍然不同)直接执行脚本和包名称从)。


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

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.

解决方案

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).

这篇关于如何知道python脚本是否使用解释器的-m选项运行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆