Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replacing imp with importlib maintaining old behavior?

I inherited some code that I need to rework since it is using deprecated imp module instead of importlib

To test the functionality I have created a simple test script:

# test.py
def main():
    print("main()")


if __name__ == "__main__":
    print("__main__")
    main()

When I run that with the old code (below as a minimal example)

# original imp based minimal example
import imp
import os
import site

script = r"./test.py"
script_dir = os.path.dirname(script)
script_name = os.path.splitext(os.path.basename(script))[0]

site.addsitedir(script_dir)

fp, pathname, description = imp.find_module(script_name, [script_dir])
imp.load_source('__main__', pathname, fp)

Would output the following:

__main__
main()

Now I have some trouble mimicking this verbatim using the importlib module since I do not get the output as above with the following code:

# my try so far using importlib
import importlib
import os
import site

script = os.path.abspath(r"./test.py")
script_dir = os.path.dirname(script)
script_name = os.path.splitext(os.path.basename(script))[0]

site.addsitedir(script_dir)

spec = importlib.util.spec_from_file_location(script_name, script)
module = importlib.util.module_from_spec(spec)
sys.modules[script_name] = module
spec.loader.exec_module(module)

Instead it outputs nothing. :-( Any suggestions on how to mimic the old (imp) behavior using importlib?

like image 309
Jonathan Avatar asked Jul 29 '26 12:07

Jonathan


1 Answers

It seems like the SourceFileLoader would meet your needs:

from importlib.machinery import SourceFileLoader

script_path = os.path.abspath(r"./test.py")
foo = SourceFileLoader("my_script", script_path).load_module()
foo.do_stuff()
like image 178
Cyrus Avatar answered Jul 31 '26 00:07

Cyrus