Halfcent
Halfcent

Reputation:

Import Dynamically Created Python Files

I am creating python files through the course of running a python program. I then want to import these files and run functions that were defined within them. The files I am creating are not stored within my path variables and I'd prefer to keep it that way.

Originally I was calling the execFile(<script_path>) function and then calling the function defined by executing the file. This has a side effect of always entering the if __name__ == "__main__" condition, which with my current setup I can't have happen.

I can't change the generated files, because I've already created 100's of them and don't want to have to revise them all. I can only change the file that calls the generated files.

Basically what I have now...

#<c:\File.py>
def func(word):
   print word

if __name__ == "__main__":
   print "must only be called from command line"
   #results in an error when called from CallingFunction.py
   input = sys.argv[1]

#<CallingFunction.py>
#results in Main Condition being called
execFile("c:\\File.py")
func("hello world")

Upvotes: 2

Views: 2271

Answers (2)

Alex Martelli
Alex Martelli

Reputation: 882451

If I understand correctly your remarks to man that the file isn't in sys.path and you'd rather keep it that way, this would still work:

import imp

fileobj, pathname, description = imp.find_module('thefile', 'c:/')
moduleobj = imp.load_module('thefile', fileobj, pathname, description)
fileobj.close()

(Of course, given 'c:/thefile.py', you can extract the parts 'c:/' and 'thefile.py' with os.path.spliy, and from 'thefile.py' get 'thefile' with os.path.splitext.)

Upvotes: 3

Martin v. L&#246;wis
Martin v. L&#246;wis

Reputation: 127527

Use

m = __import__("File")

This is essentially the same as doing

import File
m = File

Upvotes: 5

Related Questions