1

First of all, a little bit of context I was using importlib to modify an import and was trying to find a solution for modifying an imported file. I saw an answer suggesting that for arbitrarily modifying an imported module you can use this code

def modify_and_import(module_name, package):
    spec = importlib.util.find_spec(module_name, package)
    source = spec.loader.get_source(module_name)
    new_source = tokens.tokenize(source)
    module = importlib.util.module_from_spec(spec)
    codeobj = compile(new_source, module.__spec__.origin, 'exec')
    exec(codeobj, module.__dict__)
    sys.modules[module_name] = module
    return module

Now I ran it with the following call

o = modify_and_import('o', "./o.xran")

but, running it through an exec gives me the following error

AttributeError: 'NoneType' object has no attribute 'loader'

Then I tried to print 'spec' but got None so, I think spec is returning while a file named o.xran exists.

James Z
  • 12,209
  • 10
  • 24
  • 44

2 Answers2

0

Ok, after a day I finally made it work and since I was only working with local files, I didn't need to use imp at all. Here's my final code

with open(module_name) as f:
  source = f.read()
source = tokens.tokenize(source)
module = types.ModuleType(module_name)
exec(source, module.__dict__)
sys.modules[module_name] = module
return module

Thanks to anyone who answered or tried to contribute.

-1

bro,open the modified module in your text editor,in the same window in which your project is opened,then in your project import it using,'from import *'..hope it will works..thanx

Afzaal Ahmad
  • 1
  • 1
  • 1