[英]execfile() in python , using it for user input
我正在嘗試從用戶那里獲取文件名,然后使用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。
刪除導入並執行文件名。 您需要使用.py擴展名使用此方法, if __name__ == '__main__'
部分,它將運行任何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)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.