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.

jchanger
  • 739
  • 10
  • 29
user1801279
  • 1,743
  • 5
  • 24
  • 40
  • You already import the file, you now have executable code, why the need to run the *module* through the `execfile()` function? – Martijn Pieters Dec 07 '12 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 – user1801279 Dec 07 '12 at 20:57
  • related: [log syntax errors and uncaught exceptions](http://stackoverflow.com/a/12616304/4279). – jfs Dec 07 '12 at 21:33

1 Answers1

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)
jfs
  • 399,953
  • 195
  • 994
  • 1,670
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251
  • Thank you , If possible could you just give me a hint on where I went wrong? – user1801279 Dec 07 '12 at 21:02
  • 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 – user1801279 Dec 08 '12 at 05:40