python:导入一个不是有效标识符的文件?

时间:2012-03-14 15:26:26

标签: python import python-2.7

我有一个脚本“7update.py”并想导入它。有没有办法做到这一点?我不能只键入import 7update,因为它以数字开头,因此它不是有效的标识符。我尝试过使用import('7update'),但这不起作用。

3 个答案:

答案 0 :(得分:4)

您可以,但您必须通过有效的标识符来引用它,例如:

__import__('7update')
sevenupdate = sys.modules['7update']

答案 1 :(得分:4)

seven_up = __import__("7update")

seven_up是有效的标识符,你将在你的python代码中使用该模块。

答案 2 :(得分:1)

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