0

How to using imp.load_source in python 3.4+

I use imp.load_source as follows:

setting = imp.load_source('setting', '/home/abc/setting.py')
print(setting.color) # get attribute color in setting file

but in python 3.4+, imp module has deprecated and change to use importlib module

I tried using SourceFileLoader

from importlib.machinery import SourceFileLoader

setting = SourceFileLoader('setting', '/home/abc/setting.py')
print(setting.color)

but output

AttributeError: 'SourceFileLoader' object has no attribute color

What method in importlib has the same feature imp.load_source?

Peter
  • 120
  • 1
  • 8
  • Can you explain your use case? If you really want to execute code from aribitrary source files, you might want to just use `open` to read the text and `exec` to execute it. But that's an extremely uncommon use case, and one that is going to be a security vulnerability far more often than not. – Daniel Pryden Jun 26 '19 at 01:20
  • If you just want to parse *data* using Python semantics, you might want `ast.literal_eval` instead. – Daniel Pryden Jun 26 '19 at 01:21
  • @DanielPryden, I have setting.py have constant variable, I want to load them to use. Follow documentation from python ```imp``` move to ```importlib```, but I can't see any method same ```load_source``` in ```importlib``` – Peter Jun 26 '19 at 01:25
  • 1
    From https://github.com/pyinvoke/invoke/issues/214 can you give the following a try: `from importlib.machinery import SourceFileLoader; mymodule = SourceFileLoader('modname', '/path/to/file.py').load_module()` –  Jun 26 '19 at 01:27
  • 1
    @Peter: For what it's worth, it sounds like you have the security vulnerability I was describing: you might *expect* that your `settings.py` file only contains "constant variables" but you don't *know* that, and you can't tell without executing code, which could do anything that your program has the power to do. This means that your `settings.py` file is not *data*, it's *code*, and the safe way to deploy code is to make it a part of one of your application's packages. – Daniel Pryden Jun 26 '19 at 12:54
  • @DanielPryden, I'm a newbie and I don't know _security vulnerability_ meaning, could you tell me more details or suggest me some books about security. – Peter Jun 27 '19 at 14:14

0 Answers0