2014-02-07 44 views
1

這是a.py看起來如何導入另一個作爲命令行參數提供的python文件?

import sys 


def test_import(another_python_file): 
    import another_python_file as b 
    b.run_me() 

if __name__ == '__main__': 
    print sys.argv 
    test_import(sys.argv[1].strip()) 

這是b.py看起來

def run_me(): 
    print 'I am script b' 

當我跑,我得到

$ python a.py b.py 
['a.py', 'b.py'] 
Traceback (most recent call last): 
    File "a.py", line 10, in <module> 
    test_import(sys.argv[1].strip()) 
    File "a.py", line 5, in test_import 
    import another_python_file as b 
ImportError: No module named another_python_file 

我需要什麼? 我希望它進口b.py和打印I am script b

我錯過了什麼?

+0

[可能重複](http://stackoverflow.com/questions/301134/dynamic-module-import-in-python) – msvalkon

回答

0

如果你並不需要的靈活性,你可以簡單地使用__import__('module_name')。如果您需要緩存控制,模塊搜索或重新加載等高級功能,請使用the imp module

相關問題