2

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.

3
  • You already import the file, you now have executable code, why the need to run the module through the execfile() function? Commented Dec 7, 2012 at 20:51
  • This is being run in another program , I have no idea what the code is in the program ( whose name the user enters) , so I want to execute it and catch exceptions . Since I do not know what the main is in the undefined function , I need to execute it once Commented Dec 7, 2012 at 20:57
  • related: log syntax errors and uncaught exceptions. Commented Dec 7, 2012 at 21:33

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you , If possible could you just give me a hint on where I went wrong?
Yes , I apologise for that , I stripped it on purpose because of the fact that I do not know if the user will enter the extension .py . so just to be sure I take the input , strip it and append a .py to it

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.