2012-03-14 32 views
2

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

+1

非常类似的问题[这里](http://stackoverflow.com/questions/9090079/in-python-how-to-import-filename-starts-with-a-number) - 好吧,它是“8puzzle”而不是“7update”。 – DSM 2012-03-14 15:39:56

+0

由于你的问题+1学到了一些东西。 – 2012-03-14 15:40:11

+0

@DSM:谢谢,投票结束 – 2012-03-14 15:41:56

回答

4
seven_up = __import__("7update") 

哪里seven_up是你要有效的标识符在你的Python代码中使用该模块。

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

可以,但你必须是有效的标识符引用它,这样的:

__import__('7update') 
sevenupdate = sys.modules['7update'] 
相关问题