2012-12-07 29 views
2

我試圖從用戶中提取一個文件名,然後使用execfile()來執行該文件。下面是我的代碼:Python中的execfile(),使用它作爲用戶輸入

print "Please enter the name of the file" 
filename = raw_input().split(".")[0] 
module = __import__(filename) 
execfile(module)    <-- this is where I want to execute the file 

我明白execfile()工作如下:

execfile("example.py") 

我就當文件名作爲變量傳遞如何做到這一點不確定。我正在使用Python 2.7。

+0

您已經導入文件,您現在有可執行代碼,爲什麼需要通過'execfile()'函數運行* module *? –

+0

這是在另一個程序中運行,我不知道程序中的代碼是什麼(用戶輸入其名稱),所以我想執行它並捕獲異常。由於我不知道主函數在未定義的函數中,我需要執行一次 – user1801279

+0

相關的操作:[log syntax errors and uncaught exceptions](http://stackoverflow.com/a/12616304/4279)。 – jfs

回答

4

刪除導入並執行文件名。您需要.py擴展名用這種方法,它會運行任何if __name__ == '__main__'部分:

filename = raw_input("Please enter the name of the file: ") 
execfile(filename) 

如果你只是想將其導入,則需要剝離「的.py」,它會執行if __name__ == '__main__'部分:

filename = raw_input("Please enter the name of the file: ").split(".")[0] 
module = __import__(filename) 
+0

謝謝,如果可能的話,你能否告訴我我出錯的地方? – user1801279

+0

是的,我爲此道歉,因爲我不知道用戶是否會輸入擴展名.py,所以我故意刪除它。所以只是爲了確保我接受輸入,去掉它並將一個.py添加到它 – user1801279

相關問題