Python references the contents of each file in the directory

  • Requirement example
    There is a config directory, and if you want to pass it, from config import XXXyou can refer to the variables set in the following three files:
    insert image description here
  • Goal
    We need a result like this:

In [2]: from config import A,DD,CC
In [3]: A
Out[3]: 1

  • Error Demonstration
    The current direct reference, the result is as follows:
    insert image description here

  • full demo

  • Method 1:
    1. Create a directory:
    mkdir config_test
    2. Enter the directory, create config and shell scripts:

    cd config_test/
    mkdir config
    touch update_config.sh
    

    insert image description here
    Write script: vim update_config.sh
    content is as follows:

      		for i in config/*.py;do 
      		echo $i|grep -v '__init__'|sed 's#config/\(.*\).py#from .\1 import *#g';
      		done > config/__init__.py			
    

    3. Create the config directory and enter:
    vim b.py
    A = 1
    vim c.py
    CC = 1
    vim d.py
    DD = 2
    vim init .py, nothing is written in it, the status quo:
    insert image description here
    4. Return to the config_test directory, execute:
    sh update_config.sh ;cat config/__init__.py
    the result display:
    insert image description here
    5. Quote
    insert image description here

In this way, the content in the directory file can be referenced, but in this way, as long as a new file is added, the script must be executed again.

So we need a more convenient way to add new files and automatically scan the contents of this directory. The details are as follows

  • Method 2:
    The directory structure is the same as before, no changes are made, and the content of __init__.py is changed, and the shell script update_config.sh does not need
    init.py The content is as follows:
# __init__.py for config

def main():
    import importlib
    import os
    cwd = os.path.dirname(os.path.abspath(__file__))

    files = os.listdir(cwd)

    for i in files:
        if not i.startswith('_') and i.endswith('.py'):
            m = '.' + i[:-3]

            # get a handle on the module
            mdl = importlib.import_module(m, __package__)

            # is there an __all__?  if so respect it
            if "__all__" in mdl.__dict__:
                names = mdl.__dict__["__all__"]
            else:
                # otherwise we import all names that don't begin with _
                names = [x for x in mdl.__dict__ if not x.startswith("_")]

            # now drag them in
            globals().update({k: getattr(mdl, k) for k in names})
            globals().pop(i[:-3])

main()
globals().pop('main')

This code can automatically read the content of the file in the newly added directory. After adding it, you can directly quote it. The result example:
insert image description here
the result is reproduced~~~

Guess you like

Origin blog.csdn.net/quanqxj/article/details/86715231