简体   繁体   English

名称中带有破折号或连字符 (-) 的 Python 模块

[英]Python module with a dash, or hyphen (-) in its name

I have an existing python module with a dash in its name, foo-bar.py我有一个现有的 python 模块,名称中带有一个破折号,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.) (我确实理解这不是最佳实践。但是对于这种情况,我宁愿不重新设计和测试更大的应用程序集。此外,我认为我的公司主人不会同意我花时间实施这样的变化。)

You can do that using __import__() .您可以使用__import__()来做到这__import__() For example:例如:

foobar = __import__("foo-bar")

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.这样您就可以避免在模块的文件名与程序中使用的标识符不同的情况下混淆。

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__() .我知道这个问题已经得到了提问者的满意回答,但这是另一个我认为使用__import__()有一些优点的答案。

import importlib
mod = importlib.import_module("path.to.my-module")
# mod.yourmethod()

According to the docs:根据文档:

"This provides an implementation of import which is portable to any 
Python interpreter. This also provides an implementation which is 
easier to comprehend than one implemented in a programming language 
other than Python."

Python 2.7 + onlyPython 2.7 +

Try using underscore instead of a hyphen.尝试使用下划线而不是连字符。

import pymysql_utils导入 pymysql_utils

worked for me even though import pymysql-utils was the name of the module used by pip即使 import pymysql-utils 是 pip 使用的模块的名称,它也为我工作

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM