[英]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.