pythonpython-importpython-module

Get modules in a module - Python


I have this structure:

project/
    sources/
        __init__.py
        source_one.py
        source_teo.py
    main.py

Then in main.py

import sources

# Here I'd like to get a list with [source_one, source_two]

Then import them dynamically.

Is there any way to get this?

EDIT

What I get from dir(sources):

if I do import sources I get ['__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

If I do from sources import * I get ['__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__']

If I do from sources import source_one I get ['__author__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', '__path__', 'source_one']

But, I don't know the name of files in sources package, this is only an example. How can I find them?


Solution

  • It's kind of trick ;) but works:

    import os
    fileslist = os.listdir("sources")
    for item in fileslist:
        if item.endswith("py") and item != "__init__.py":
            exec ("from sources.%s import *" %(item.split('.')[0]))