【问题标题】:python: importing a file that is not a valid identifier?python:导入不是有效标识符的文件?
【发布时间】:2012-03-14 15:26:26
【问题描述】:
我有一个脚本“7update.py”并想导入它。有没有办法做到这一点?我不能只输入import 7update,因为它以数字开头,所以它不是有效的标识符。我试过使用import('7update'),但这不起作用。
【问题讨论】:
-
非常相似的问题here——嗯,它是“8puzzle”而不是“7update”..
-
-
标签:
python
import
python-2.7
【解决方案1】:
seven_up = __import__("7update")
seven_up 是您将在该模块的 Python 代码中使用的有效标识符。
【解决方案2】:
你可以,但你必须通过一个有效的标识符来引用它,就像这样:
__import__('7update')
sevenupdate = sys.modules['7update']
【解决方案3】:
Here is an example from the docs:
import imp
import sys
def __import__(name, globals=None, locals=None, fromlist=None):
# Fast path: see if the module has already been imported.
try:
return sys.modules[name]
except KeyError:
pass
# If any of the following calls raises an exception,
# there's a problem we can't handle -- let the caller handle it.
fp, pathname, description = imp.find_module(name)
try:
return imp.load_module(name, fp, pathname, description)
finally:
# Since we may exit via an exception, close fp explicitly.
if fp:
fp.close()