Generate config from config str. Args: cfg_str (str): Config str. file_format (str): Config file format corresponding to the config str. Only py/yml/yaml/json type are supported now! Returns: :obj:`Config`: Config obj.
(cfg_str, file_format)
| 172 | |
| 173 | @staticmethod |
| 174 | def from_string(cfg_str, file_format): |
| 175 | """Generate config from config str. |
| 176 | |
| 177 | Args: |
| 178 | cfg_str (str): Config str. |
| 179 | file_format (str): Config file format corresponding to the |
| 180 | config str. Only py/yml/yaml/json type are supported now! |
| 181 | |
| 182 | Returns: |
| 183 | :obj:`Config`: Config obj. |
| 184 | """ |
| 185 | if file_format not in ['.py', '.json', '.yaml', '.yml']: |
| 186 | raise IOError('Only py/yml/yaml/json type are supported now!') |
| 187 | if file_format != '.py' and 'dict(' in cfg_str: |
| 188 | # check if users specify a wrong suffix for python |
| 189 | logger.warning( |
| 190 | 'Please check "file_format", the file format may be .py') |
| 191 | with tempfile.NamedTemporaryFile( |
| 192 | 'w', encoding='utf-8', suffix=file_format, |
| 193 | delete=False) as temp_file: |
| 194 | temp_file.write(cfg_str) |
| 195 | # on windows, previous implementation cause error |
| 196 | # see PR 1077 for details |
| 197 | # `from_string` materializes a caller-provided in-process string into |
| 198 | # a tempfile; the threat model for `trust_remote_code` does not apply. |
| 199 | cfg = Config.from_file(temp_file.name, trust_remote_code=True) |
| 200 | os.remove(temp_file.name) |
| 201 | return cfg |
| 202 | |
| 203 | def __init__(self, cfg_dict=None, cfg_text=None, filename=None): |
| 204 | if cfg_dict is None: |