2011-12-21 28 views
2

我写测试仪进入运行用户脚本:导入文件由用户

tester d:\scripts\test_scripts_list.txt 

的test_scripts_list.txt看起来是这样的:

test1 
d:\123\test2 

我的程序读取与命令行模块模块,读取test_scripts_list.txt的每一行,并导入每个测试文件与__import__(实际运行测试文件)。
这是行之有效的。

我唯一的问题是导入d:\ 123 \ TEST2这是给我:

ImportError: Import by filename is not supported. 

我认为这是可以通过分析路径名来解决,把它添加到PYTHONPATHsys.path.append和运行时比导入它。但它似乎是一个复杂的灵魂。
你有更好的主意吗?

注:TEST1的路径已经在PYTHONPATH

编辑 我目前的解决方案:

# Go over each line in scripts_filename and import all tests 
for line in open(scripts_file.scripts_filename): 
    line = line.strip() 

    if not line or line[0] == '#': 
     # Ignore empty line and line with comment 
     continue 
    elif line[1] == ':' and line[2] == '\\': 
     # Find the last position of '\\' 
     file_name_pos = line.rfind('\\') 
     # Separate file path and filename (I.E [0:5] will take 4 first chars and [4:] will take all chars except the 4 chars) 
     file_path_string = line[0:file_name_pos+1] 
     file_name_string = line[file_name_pos+1:] 
     # Append file_path_string to PYTHONPATH in order to import it later 
     sys.path.append(file_path_string) 

     import_name = file_name_string 
    else: 
     import_name = line 

    try: 
     # Try to import test 
     print "Run test : %s" % line 
     __import__(import_name) 
    except ImportError: 
     print "Failed! (Test not found). Continue to the next test" 

回答

3

imp module,特别是imp.load_moduleimp.load_source功能。这里有一种方法,你可以用它们(从Mercurial的source code,稍作简化):

def loadpath(path): 
    module_name = os.path.basename(path)[:-3] 
    if os.path.isdir(path): 
     # module/__init__.py style 
     d, f = os.path.split(path.rstrip('/')) 
     fd, fpath, desc = imp.find_module(f, [d]) 
     return imp.load_module(module_name, fd, fpath, desc) 
    else: 
     return imp.load_source(module_name, path) 
+0

看来我还需要分析文件中的行,单独的路径和模块的名称,然后右键打电话给你function.am我? – 2011-12-21 09:27:25

+0

现在我的灵魂是:file_name_pos = line.rfind('\\')file_path_string = line [0:file_name_pos + 1] file_name_string = line [file_name_pos + 1:] sys.path.append(file_path_string) – 2011-12-21 09:29:51

+0

模块名称可以基本上任何东西。我已经更新了答案,以显示计算它的一种方式。 – 2011-12-21 11:13:30