我試圖從用戶中提取一個文件名,然後使用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。
您已經導入文件,您現在有可執行代碼,爲什麼需要通過'execfile()'函數運行* module *? –
這是在另一個程序中運行,我不知道程序中的代碼是什麼(用戶輸入其名稱),所以我想執行它並捕獲異常。由於我不知道主函數在未定義的函數中,我需要執行一次 – user1801279
相關的操作:[log syntax errors and uncaught exceptions](http://stackoverflow.com/a/12616304/4279)。 – jfs