admin管理员组

文章数量:1287791

I really need to solve my problem because one of the scripts I built, there are hundreds of variables; and in the other script, I don't want to import all variables but only specific variables using Regex; but it seems there is no way how to do.

I'll give an example, there are two scripts, the first one is script_load.py and the second is script_main.py

script_load.py

import os
from configparser import ConfigParser

file = os.path.join(os.getcwd(), 'file.txt')
fparser = ConfigParser()
fparser.read(file)
COLOUR_ONE = fparser.get("GENERAL", "Green")
COLOUR_TWO = fparser.get("GENERAL", "Red")
COLOUR_THREE = fparser.get("GENERAL", "Blue")
BUILDING_ONE = fparser.get("GENERAL", "House")
BUILDING_TWO = fparser.get("GENERAL", "School")
BUILDING_THREE = fparser.get("GENERAL", "Supermarket")

script_main.py

from script_load import r'^COLOUR.+$'

def function():
    global r'^COLOUR.+$'

    print(COLOUR_ONE+COLOUR_TWO+COLOUR_THREE)

As the above, I want to use a syntax like import r'^COLOUR.+$' instead of import * to filter variables as imported. However, I tested and it got error as the following output:

SyntaxError: invalid syntax

Note: What I want is to use the same variables in script_main.py as in script_load.py, not to create new variables because in my problem as I said at the beginning, there are hundreds of variables and I don't want to fill up new variables in script_main.py, besides to import all variables from script_load.py into script_main.py, some of variables could be combined and it will not work fine; So, the post "How can I import a module dynamically given its name as string?" as someone suggested me, it doesn't work me.

I really need to solve my problem because one of the scripts I built, there are hundreds of variables; and in the other script, I don't want to import all variables but only specific variables using Regex; but it seems there is no way how to do.

I'll give an example, there are two scripts, the first one is script_load.py and the second is script_main.py

script_load.py

import os
from configparser import ConfigParser

file = os.path.join(os.getcwd(), 'file.txt')
fparser = ConfigParser()
fparser.read(file)
COLOUR_ONE = fparser.get("GENERAL", "Green")
COLOUR_TWO = fparser.get("GENERAL", "Red")
COLOUR_THREE = fparser.get("GENERAL", "Blue")
BUILDING_ONE = fparser.get("GENERAL", "House")
BUILDING_TWO = fparser.get("GENERAL", "School")
BUILDING_THREE = fparser.get("GENERAL", "Supermarket")

script_main.py

from script_load import r'^COLOUR.+$'

def function():
    global r'^COLOUR.+$'

    print(COLOUR_ONE+COLOUR_TWO+COLOUR_THREE)

As the above, I want to use a syntax like import r'^COLOUR.+$' instead of import * to filter variables as imported. However, I tested and it got error as the following output:

SyntaxError: invalid syntax

Note: What I want is to use the same variables in script_main.py as in script_load.py, not to create new variables because in my problem as I said at the beginning, there are hundreds of variables and I don't want to fill up new variables in script_main.py, besides to import all variables from script_load.py into script_main.py, some of variables could be combined and it will not work fine; So, the post "How can I import a module dynamically given its name as string?" as someone suggested me, it doesn't work me.

Share Improve this question edited Feb 23 at 0:44 luisito_36 asked Feb 22 at 21:24 luisito_36luisito_36 1051 silver badge4 bronze badges 6
  • "it seems there is no way how to do" - correct. That's simply not supported by the import statement. It seems like what you actually want is some enums, so you can add only the ones you need to the namespace (e.g. from script_load import Colour then Colour.ONE). – jonrsharpe Commented Feb 22 at 21:33
  • 2 Just import script_load and then colours = {key: value for key, value in vars(script_load).items() if key.startswith("COLOUR")}. You won't avoid loading the module anyway. – Wiktor Stribiżew Commented Feb 22 at 21:37
  • You need more structure in your data. If you are trying to access groups of variables of similar names, it's a sign that they should be part of something like a dict. – Thierry Lathuille Commented Feb 22 at 22:29
  • This question is similar to: How can I import a module dynamically given its name as string?. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – JonSG Commented Feb 22 at 22:38
  • Thanks all of you to help me, I see that the only way that works me is: from script_main import COLOUR_ONE, COLOUR_TWO, COLOUR_THREE – luisito_36 Commented Feb 23 at 0:46
 |  Show 1 more comment

1 Answer 1

Reset to default 3

You can probably do it with importlib and then adding the variables to the global scope:

import importlib
import re


def dynamic_import(pattern: re.Pattern, name: str) -> None:
    module = importlib.import_module(name)

    for attr in dir(module):
        match = pattern.match(attr)
        if not match:
            continue

        globals()[attr] = getattr(module, attr)
    del module


dynamic_import(repile('COLOUR_.*'), 'script_load')

print(dir())  # show the variables in global namespace

本文标签: How to filter variables for import in PythonStack Overflow