简体   繁体   中英

python importlib imports from wrong directory

I am trying to import dicts named 'tasks' from different python files (*.py).

The paths are stored in my array directories['code'] . Not all files contain one of these tasks dicts.

The problem is, once a file with a dict was found, 'foo' will be set to that dict, but won't be reset , even if the next file does not have a dict.

However, 'foo' will be assigned correctly again, once another file was found containing a new dict.

I wonder if this is because importlib is searching an entire tree, not just the exact path?

And of course, how can I fix this?

import importlib

for i in range(len(directories['code'])):

    try:
        foo = importlib.machinery.SourceFileLoader('file', directories['code'][i]).load_module().tasks

    except:
        foo = '0'
        pass

    print(foo)

Your code is valid, there is one place where is something goes wrong -- directories['code'][i] , -- so try to use i :

for i in ['test/__init__.py', 'test/__init__2.py']:
    try:
        foo = importlib.machinery.SourceFileLoader('file', i).load_module().__version__
    except:
        foo = 0
    print(i, foo)

# test/__init__.py 1.0.0
# test/__init__2.py 0

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM