Python run from subdirectory

2024/11/19 14:28:56

I have the following file hierarchy structure:

main.py
Main/A/a.pyb.pyc.pyB/a.pyb.pyc.pyC/a.pyb.pyc.py

From main.py I would like to execute any of the scripts in any of the subfolders.

The user will pass on a string A_a.py or B_a.py. The string will be parsed and changed into A/a.py or B/a.py

I would like the approach to be dynamic, such that adding any subfolder for e.g. D with a.py, b.py and c.py would directly adapt without forcing any import lines to the main.py script.

I know it could be done using shell calls like pOpen. But would like to execute it within the code.

Is it possible?

Answer

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 sysbase = '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 + '.' + nametry:return import_module(full_name)except ImportError as e:print edef main():# D is not listedprint os.listdir(base)# works for Amod = get_module('A_a.py')if mod:mod.f()# can also call like thismod.__dict__['f']()# doesn't work for Dmod = 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 eif e.errno != errno.EEXIST:sys.exit(-1)# D should be listedprint os.listdir(base)# should work for Dmod = 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
https://en.xdnf.cn/q/119941.html

Related Q&A

How to create duplicate for each value in a python list given the number of dups I want?

I have this list: a=[7086, 4914, 1321, 1887, 7060]. Now, I want to create duplicate of each value n-times. Such as: n=2a=[7086,7086,4914,4914,1321,1321,7060,7060]How would I do this best? I tried a lo…

How do I generate random float and round it to 1 decimal place

How would I go about generating a random float and then rounding that float to the nearest decimal point in Python 3.4?

Error extracting text from website: AttributeError NoneType object has no attribute get_text

I am scraping this website and get "title" and "category" as text using .get_text().strip().I have a problem using the same approach for extracting the "author" as text.d…

Fastest way to extract tar files using Python

I have to extract hundreds of tar.bz files each with size of 5GB. So tried the following code:import tarfile from multiprocessing import Poolfiles = glob.glob(D:\\*.tar.bz) ##All my files are in D for …

Python - Split a string but keep contiguous uppercase letters [duplicate]

This question already has answers here:Splitting on group of capital letters in python(3 answers)Closed 3 years ago.I would like to split strings to separate words by capital letters, but if it contain…

Python: Find a Sentence between some website-tags using regex

I want to find a sentence between the ...class="question-hyperlink"> tags. With this code:import urllib2 import reresponse = urllib2.urlopen(https://stackoverflow.com/questions/tagged/pyth…

How to download all the href (pdf) inside a class with python beautiful soup?

I have around 900 pages and each page contains 10 buttons (each button has pdf). I want to download all the pdfs - the program should browse to all the pages and download the pdfs one by one. Code only…

Reducing the complexity/computation time for a basic graph formula [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.Want to improve this question? Add details and clarify the problem by editing this post.Closed 4 years ago.Improve…

Find All Possible Fixed Size String Python

Problem: I want to generate all possible combination from 36 characters that consist of alphabet and numbers in a fixed length string. Assume that the term "fixed length" is the upper bound f…

What is the concept of namespace when importing a function from another module?

main.py:from module1 import some_function x=10 some_function()module1.py:def some_function():print str(x)When I execute the main.py, it gives an error in the moduel1.py indicating that x is not availab…