tags:

views:

198

answers:

2

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")
+4  A: 

Use

m = __import__("File")

This is essentially the same as doing

import File
m = File
Martin v. Löwis
It's indeed the same, and so doesn't solve Halfcent's problem if I read correctly his "files I am creating are not stored within my path variables and I'd prefer to keep it that way" remark.
Alex Martelli
Or just disregard the unhelpful constraint. The files can be put in a subpackage, out of the way of the other modules in your project's root package.
Aaron Gallagher
+1  A: 

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.)

Alex Martelli