2

我正在尝试从用户那里获取文件名,然后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。

4

1 回答 1

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)
于 2012-12-07T20:59:21.200 回答