Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Load source file without a module

Tags:

python

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 (it will be passed to to code by the command line or something like that), 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.

like image 290
R.Mckemey Avatar asked Jan 07 '23 01:01

R.Mckemey


1 Answers

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

like image 165
Enrique GR Avatar answered Jan 08 '23 15:01

Enrique GR