execfile() in python , using it for user input

user1801279 picture user1801279 · Dec 7, 2012 · Viewed 10.6k times · Source

I am trying to take in a filename from a user and then use execfile() to execute the file. Below is my code:

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

I understand that execfile() works as follows:

execfile("example.py")

I am unsure on how to do this when the filename is passed as a variable . I am using python 2.7.

Answer

Mark Tolonen picture Mark Tolonen · Dec 7, 2012

Drop the import and exec the filename. You need the .py extension with this method and it will run any if __name__ == '__main__' section:

filename = raw_input("Please enter the name of the file: ")
execfile(filename)

If you just want to import it, you need to strip the '.py' and it will not execute an if __name__ == '__main__' section:

filename = raw_input("Please enter the name of the file: ").split(".")[0]
module = __import__(filename)