R.Mckemey R.Mckemey - 6 months ago 39
Python Question

Load source file without a module

I want to pass my program a file and get a function out of it.

For example, I have a file,

foo.py
, who's location is not known until run time, can be anywhere on my system and looks like this:

def bar():
return "foobar"


how can I get my code to run the function
bar
?

If the location was known before run time I could do this:

import sys
sys.path.append("path_to_foo")
import foo

foo.bar()


I could create an
init.py
file in the folder where
foo.py
is and use
importlib
or
imp
but it seems messy. I can't use
__import__
as I get
ImportError: Import by filename is not supported.

Answer

You could open the file and execute it using exec.

f = open('foo.py')
source = f.read()
exec(source)
print bar()

You could even look for the specific function using re