我正在尝试从用户接收文件名,然后使用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 :(得分: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)