Python Run From Subdirectory
I have the following file hierarchy structure: main.py Main/ A/ a.py b.py c.py B/ a.py b.py c.py C/
Solution 1:
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:
deff():
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'defget_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
defmain():
# D is not listedprint 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 Dtry:
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 listedprint 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 modulenamedD.a
['__init__.py', '__init__.pyc', 'D', 'A']
Main.D.a
Main.D.a
Solution 2:
If you don't want to use any import statement then use os
module
This can be done using os.system(command)
# main.py
# string = A_a.py, B_b.py
string = raw_input("Enter file to run ")
dirname = string[:1]
filename = string[2:]
os.chdir('Main/'+dirname)
os.system('python %s' %filename)
That is another case if the file/directory doesn't exist.
Post a Comment for "Python Run From Subdirectory"