[Solved] Python run from subdirectory


I added empty __init__.py files to Main/, A/, B/, and C/. I also put the following function in each of the .py files just so we had something to call:

def f():
    print __name__

In main.py, the significant function is get_module, which calls import_module from importlib.

import errno
from importlib import import_module
import os
from shutil import copytree
import sys

base="Main"

def get_module(arg):
    # 'X_x.py' becomes 'X.x'
    name = arg.strip('.py').replace('_', '.')
    # full_name will be 'Main.X.x'
    full_name = base + '.' + name
    try:
        return import_module(full_name)
    except ImportError as e:
        print e

def main():
    # D is not listed
    print os.listdir(base)
    # works for A
    mod = get_module('A_a.py')
    if mod:
        mod.f()
        # can also call like this
        mod.__dict__['f']()
    # doesn't work for D
    mod = get_module('D_a.py')
    if mod:
        mod.f()
        mod.__dict__['f']()
    # copy files from A to D
    try:
        copytree(os.path.join(base, 'A'),
                 os.path.join(base, 'D'))
    except OSError as e:
        print e
        if e.errno != errno.EEXIST:
            sys.exit(-1)
    # D should be listed
    print os.listdir(base)
    # should work for D
    mod = get_module('D_a.py')
    if mod:
        mod.f()
        mod.__dict__['f']()

if __name__ == '__main__':
    main()

If all goes well this should be the output:

$ python2.7 main.py
['__init__.py', '__init__.pyc', 'A']
Main.A.a
Main.A.a
No module named D.a
['__init__.py', '__init__.pyc', 'D', 'A']
Main.D.a
Main.D.a

solved Python run from subdirectory