本文介绍了Python从子目录运行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有以下文件层次结构:

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/
         a.py
         b.py
         c.py

在main.py中,我想在任何子文件夹中执行任何脚本.

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

用户将传递字符串A_a.py或B_a.py.该字符串将被解析并更改为A/a.py或B/a.py

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

我希望这种方法是动态的,以便添加任何子文件夹,例如带有a.py,b.py和c.py的D可以直接进行修改,而不会强制对main.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.

我知道可以使用像pOpen这样的shell调用来完成.但是想在代码中执行它.

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

有可能吗?

推荐答案

我将空的 __ init __.py 文件添加到 Main/,A/,B/和C/.我还在每个 .py 文件中放置了以下函数,以便我们可以调用一些东西:

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__

main.py 中,重要的功能是get_module,它调用 importlib中的import_module .

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

这篇关于Python从子目录运行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-23 05:51
查看更多