diff --git a/mmengine/config/config.py b/mmengine/config/config.py index 4645aafede..29e71a671e 100644 --- a/mmengine/config/config.py +++ b/mmengine/config/config.py @@ -335,18 +335,20 @@ def _substitute_environment_vars(filename: str, temp_config_name: str): """ with open(filename, encoding='utf-8') as f: config_file = f.read() - regexp = r'\{\{[\'\"]?\s*\$(\w+)\s*\:?\s*(\S*?)\s*[\'\"]?\}\}' + regexp = r'\{\{[\'\"]?\s*\$(\w+)\s*\:\s*(\S*?)\s*[\'\"]?\}\}' keys = re.findall(regexp, config_file) env_variables = dict() for var_name, value in keys: - regexp = r'\{\{[\'\"]?\s*\$' + var_name + r'\s*\:?\s*' \ + regexp = r'\{\{[\'\"]?\s*\$' + var_name + r'\s*\:\s*' \ + value + r'\s*[\'\"]?\}\}' if var_name in os.environ: value = os.environ[var_name] env_variables[var_name] = value - print_log(f'Using env variable `{var_name}` with value of ' - f'{value} to replace item in config.') - elif not value: + print_log( + f'Using env variable `{var_name}` with value of ' + f'{value} to replace item in config.', + logger='current') + if not value: raise KeyError(f'`{var_name}` cannot be found in `os.environ`.' f' Please set `{var_name}` in environment or ' 'give a default value.') diff --git a/tests/data/config/py_config/test_environment_var.py b/tests/data/config/py_config/test_environment_var.py index 86697d7c05..89508fb133 100644 --- a/tests/data/config/py_config/test_environment_var.py +++ b/tests/data/config/py_config/test_environment_var.py @@ -1,4 +1,4 @@ # Copyright (c) OpenMMLab. All rights reserved. -item1 = '{{ $ITEM1 }}' +item1 = '{{ $ITEM1: }}' item2 = '{{ $ITEM2:default_value }}' item3 = {{' $ITEM3:80 '}} diff --git a/tests/test_config/test_config.py b/tests/test_config/test_config.py index f1784e9740..51a7afe97c 100644 --- a/tests/test_config/test_config.py +++ b/tests/test_config/test_config.py @@ -370,7 +370,7 @@ def test_substitute_environment_vars(self, tmp_path): cfg = tmp_path / 'tmp_cfg1.py' substituted_cfg = tmp_path / 'tmp_cfg2.py' - cfg_text = 'a={{$A}}\n' + cfg_text = 'a={{$A:}}\n' with open(cfg, 'w') as f: f.write(cfg_text) with pytest.raises(KeyError):