我试图从用户那里获取一个文件名,然后使用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。
发布于 2012-12-08 04:59:21
删除导入并执行文件名。您需要使用此方法的.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)https://stackoverflow.com/questions/13770735
复制相似问题