Python 模块名称中带有破折号或连字符 (-)
我有一个现有的 python 模块,其名称中带有破折号 foo-bar.py
更改模块名称是我希望避免的事情,因为该模块是共享的,并且我必须追踪使用它的所有位置,以便我的特殊情况会起作用。
有没有办法加载名称包含通常禁止的“-”的模块?
(我确实知道这不是最佳实践。但对于这种情况,我宁愿不重新设计和测试更大的应用程序集。而且我认为我的公司大师不会批准我花时间实施这样的改变。)
I have an existing python module with a dash in its name, foo-bar.py
Changing the module name is something I would prefer to avoid as the module is shared, and I would have to chase down all the places it is used so that my special case will work.
Is there a way to load a module whose name contains the typically forbidden '-'?
(I do understand that this isn't a best practice. But for this situation I would prefer not to redesign and test a much larger set of applications. Also I don't think my corporate masters would approve of my taking the time to implement such a change.)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您可以使用
__import__()
来完成此操作。例如:但是您确实应该重命名该模块。这样,您可以避免模块的文件名与程序中使用的标识符不同的混乱。
You can do that using
__import__()
. For example:But you really should rename the module instead. That way you can avoid confusion where the filename of the module is different from the identifier used in the program.
我知道这个问题已经得到了令提问者满意的回答,但这是另一个答案,我认为它比使用
__import__()
有一些优点。根据文档:
仅
Python 2.7
+I know this question has already been answered to satisfaction of the asker, but here is another answer which I believes has some merit above using
__import__()
.According to the docs:
Python 2.7
+ only