Ram
Ram

Reputation: 115

Python Importlib loader.exec_module to run a function of a py file

I have several .py files in several folders. I do os.walk and get all names of .py files in list files and prior to that I know that each .py contains a function test() which takes an integer and returns an integer (which is somewhat unique). I am using the following code. Where r is an integer, files contain the path of a py file, for example:

C://users//codebase//user1//int_user_1.py

for fil in files:
    spec = importlib.util.spec_from_file_location("test", fil)
    foo = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(foo)
    get_test = foo.test(r)

But the problem here is the line spec.loader.exec_module(foo) is executing all the code in the file fil from line 1 of that particular .py file, but not just the function fil.test(). How can I execute only fil.test() function?

EDIT-1: I am unable to make any changes to the content of fil.py.

Upvotes: 0

Views: 3376

Answers (1)

Masklinn
Masklinn

Reputation: 42332

How can I execute only fil.test() function?

Wrap all the non-declaration code in an if __name__ == '__main__' condition.

Python modules are executable code, loading a module means executing the body of the module in a special "module namespace". If there's code you don't want executed on import, you have to "gate" it, using the condition above: a module's __name__ is only "__main__" if the module is being directly executed e.g.

$ echo "print(__name__)" > foo.py
$ python foo.py
__main__
$ python -c 'import foo'
foo

Upvotes: 1

Related Questions