当前位置: 首页>>代码示例>>Python>>正文


Python yaml.full_load方法代码示例

本文整理汇总了Python中yaml.full_load方法的典型用法代码示例。如果您正苦于以下问题:Python yaml.full_load方法的具体用法?Python yaml.full_load怎么用?Python yaml.full_load使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在yaml的用法示例。


在下文中一共展示了yaml.full_load方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: conf_to_dict

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def conf_to_dict(conf):
	result = None
	# json string?
	try:
		result = json.loads(conf)
	except:
		# json file?
		try:	
			with open(conf) as f:
				result =  json.load(f)
		except:
			# yaml file?
			try:
				with open(conf) as stream:
					result = yaml.full_load(stream)
			except:
				pass
	return result 
开发者ID:andrewekhalel,项目名称:edafa,代码行数:20,代码来源:utils.py

示例2: get_predefined_styles

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def get_predefined_styles():
    '''
    Reads all predefined styles and returns a list of names.

    Parameters : None

    Returns : (list of strings)
    '''
    lReturn = []
    sStylePath = os.path.join(os.path.dirname(__file__), 'styles')
    lStyles = os.listdir(sStylePath)
    for sStyle in lStyles:
        if sStyle.endswith('.yaml'):
            with open(os.path.join(sStylePath, sStyle)) as yaml_file:
                tempConfiguration = yaml.full_load(yaml_file)
            lReturn.append(tempConfiguration['name'])
    return lReturn 
开发者ID:jeremiah-c-leary,项目名称:vhdl-style-guide,代码行数:19,代码来源:__main__.py

示例3: open_configuration_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def open_configuration_file(sFileName, sJUnitFileName=None):
    '''Attempts to open a configuration file and read it's contents.'''
    try:
        with open(sFileName) as yaml_file:
            tempConfiguration = yaml.full_load(yaml_file)
    except IOError:
        print('ERROR: Could not find configuration file: ' + sFileName)
        write_invalid_configuration_junit_file(sFileName, sJUnitFileName)
        sys.exit(1)
    except yaml.scanner.ScannerError as e:
        print('ERROR: Invalid configuration file: ' + sFileName)
        print(e)
        write_invalid_configuration_junit_file(sFileName, sJUnitFileName)
        exit()
    except yaml.parser.ParserError as e:
        print('ERROR: Invalid configuration file: ' + sFileName)
        print(e)
        write_invalid_configuration_junit_file(sFileName, sJUnitFileName)
        exit()
    return tempConfiguration 
开发者ID:jeremiah-c-leary,项目名称:vhdl-style-guide,代码行数:22,代码来源:__main__.py

示例4: _coerce

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def _coerce(data: Union[Dict, str, Path, 'ConfigTree'], source: Union[str, None]) -> Tuple[Dict, Union[str, None]]:
        """Coerces data into dictionary format."""
        if isinstance(data, dict):
            return data, source
        elif (isinstance(data, str) and data.endswith(('.yaml', '.yml'))) or isinstance(data, Path):
            source = source if source else str(data)
            with open(data) as f:
                data = f.read()
            data = yaml.full_load(data)
            return data, source
        elif isinstance(data, str):
            data = yaml.full_load(data)
            return data, source
        elif isinstance(data, ConfigTree):
            return data.to_dict(), source
        else:
            raise ConfigurationError(f"ConfigTree can only update from dictionaries, strings, paths and ConfigTrees. "
                                     f"You passed in {type(data)}", value_name=None) 
开发者ID:ihmeuw,项目名称:vivarium,代码行数:20,代码来源:config_tree.py

示例5: validate_model_specification_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def validate_model_specification_file(file_path: Union[str, Path]) -> None:
    """Ensures the provided file is a yaml file"""
    file_path = Path(file_path)
    if not file_path.exists():
        raise ConfigurationError('If you provide a model specification file, it must be a file. '
                                 f'You provided {str(file_path)}', value_name=None)

    if file_path.suffix not in ['.yaml', '.yml']:
        raise ConfigurationError(f'Model specification files must be in a yaml format. You provided {file_path.suffix}',
                                 value_name=None)
    # Attempt to load
    with file_path.open() as f:
        raw_spec = yaml.full_load(f)
    top_keys = set(raw_spec.keys())
    valid_keys = {'plugins', 'components', 'configuration'}
    if not top_keys <= valid_keys:
        raise ConfigurationError(f'Model specification contains additional top level '
                                 f'keys {valid_keys.difference(top_keys)}.', value_name=None) 
开发者ID:ihmeuw,项目名称:vivarium,代码行数:20,代码来源:configuration.py

示例6: test_build_model_specification

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def test_build_model_specification(mocker, test_spec, test_user_config):
    expand_user_mock = mocker.patch('vivarium.framework.configuration.Path.expanduser')
    expand_user_mock.return_value = test_user_config
    loaded_model_spec = build_model_specification(test_spec)

    test_data = DEFAULT_PLUGINS.copy()

    with test_spec.open() as f:
        model_data = yaml.full_load(f)

    test_data.update(model_data)

    with test_user_config.open() as f:
        user_data = yaml.full_load(f)

    test_data['configuration'].update(user_data)

    assert loaded_model_spec.to_dict() == test_data 
开发者ID:ihmeuw,项目名称:vivarium,代码行数:20,代码来源:test_configuration.py

示例7: test_from_yaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def test_from_yaml(self):
        stream = StringIO(TEST_JSON)
        d = yaml.full_load(stream)
        d = flatten_dict(d['output_metadata'])
        self.assertEqual(17, len(d))
        self.assertEqual('DCS4COP Sentinel-3 OLCI L2C Data Cube',
                         d.get('title'))
        self.assertEqual('Brockmann Consult GmbH, Royal Belgian Institute for Natural Sciences (RBINS)',
                         d.get('creator_name'))
        self.assertEqual('https://www.brockmann-consult.de, http://odnature.naturalsciences.be/remsem/',
                         d.get('creator_url'))
        self.assertEqual("2018-05-30", d.get('date_created'))
        self.assertEqual("2018-06-01", d.get('date_issued'))
        self.assertEqual(0.0, d.get('geospatial_lon_min'))
        self.assertEqual(5.0, d.get('geospatial_lon_max'))
        self.assertEqual(50.0, d.get('geospatial_lat_min'))
        self.assertEqual(52.5, d.get('geospatial_lat_max'))
        self.assertEqual('degrees_east', d.get('geospatial_lon_units'))
        self.assertEqual('degrees_north', d.get('geospatial_lat_units'))
        self.assertEqual(0.0025, d.get('geospatial_lon_resolution'))
        self.assertEqual(0.0025, d.get('geospatial_lat_resolution'))
        self.assertEqual('2016-10-01', d.get('time_coverage_start'))
        self.assertEqual('2017-10-01T12:00:10', d.get('time_coverage_end'))
        self.assertEqual('P1Y', d.get('time_coverage_duration'))
        self.assertEqual('1D', d.get('time_coverage_resolution')) 
开发者ID:dcs4cop,项目名称:xcube,代码行数:27,代码来源:test_config.py

示例8: insert_admin

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def insert_admin():
    dirs = os.listdir()
    if 'app' in dirs:
        f = open("app/config.cfg", 'r')
    else:
        f = open("./config.cfg", 'r')
    settings = yaml.full_load(f)
    settings = settings['docker']
    mongo_client = MongoClient(settings['mongo_ip'], settings['mongo_port'])
    mongo_db = mongo_client['userinfo']
    userinfo = mongo_db['userinfo']
    f.close()

    parser = argparse.ArgumentParser(description = "Add admin user to MongoDB")
    parser.add_argument('-p', '--password', type = str, help = "Admin password", required = True)

    if userinfo.find({'username':'admin'}).count() > 0:
        print("Admin already exists")
    else:
        args = parser.parse_args()
        password = args.password
        hashed = hashpw(password.encode('utf-8'), gensalt())
        userinfo.insert_one({"username":"admin","password":hashed,"user_id":0})
        print("Successfully added an admin user with password {}!".format(password)) 
开发者ID:Nth-iteration-labs,项目名称:streamingbandit,代码行数:26,代码来源:insert_admin.py

示例9: load_type

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def load_type(obj_type, path: str):
    """Load a Kubernetes YAML manifest file for the specified type.

    While Kubernetes manifests can contain multiple object definitions
    in a single file (delimited with the YAML separator '---'), this
    does not currently support those files. This function expects a
    single object definition in the specified manifest file.

    Args:
        path: The path the manifest YAML to load.
        obj_type: The Kubernetes API object type that the YAML
            contents should be loaded into.

    Returns:
        A Kubernetes API object populated with the YAML contents.

    Raises:
        FileNotFoundError: The specified file was not found.
    """
    with open(path, 'r') as f:
        manifest = yaml.full_load(f)

    return new_object(obj_type, manifest) 
开发者ID:vapor-ware,项目名称:kubetest,代码行数:25,代码来源:manifest.py

示例10: _parse_docstring

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def _parse_docstring(obj, process_doc, from_file_keyword, base_path):
    first_line, other_lines, swag = None, None, None
    full_doc = inspect.getdoc(obj)
    if full_doc:
        if from_file_keyword is not None:
            from_file = _find_from_file(full_doc, from_file_keyword, base_path)
            if from_file:
                full_doc_from_file = _doc_from_file(from_file)
                if full_doc_from_file:
                    full_doc = full_doc_from_file
        line_feed = full_doc.find('\n')
        if line_feed != -1:
            first_line = process_doc(full_doc[:line_feed])
            yaml_sep = full_doc[line_feed+1:].find('---')
            if yaml_sep != -1:
                other_lines = process_doc(full_doc[line_feed+1:line_feed+yaml_sep])
                swag = yaml.full_load(full_doc[line_feed+yaml_sep:])
            else:
                other_lines = process_doc(full_doc[line_feed+1:])
        else:
            first_line = full_doc
    return first_line, other_lines, swag 
开发者ID:gangverk,项目名称:flask-swagger,代码行数:24,代码来源:flask_swagger.py

示例11: get_experiment_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def get_experiment_config(self, required_keys, experiment_name): 
        experiment_file_path = os.path.join(BASE_DIR, "config", "experiments", experiment_name) + ".yml"
        with open(experiment_file_path, 'r') as f:
            try:
                experiment_config_all = yaml.full_load(f)
            except yaml.YAMLError as exc:
                self.log.error("{0}: Failure loading experiment yaml {1}".format(
                    self.__class__.__name__, experiment_file_path), str(exc))
                sys.exit(1)
        if(ENV not in experiment_config_all.keys()):
            self.log.error("{0}: Cannot find experiment settings for {1} in {2}".format(
                self.__class__.__name__, ENV, experiment_file_path))
            sys.exit(1)

        experiment_config = experiment_config_all[ENV]
        for key in required_keys:
            if key not in experiment_config.keys():
                self.log.error("{0}: Value missing from {1}: {2}".format(
                    self.__class__.__name__, experiment_file_path, key))
                sys.exit(1)
        return experiment_config 
开发者ID:mitmedialab,项目名称:CivilServant,代码行数:23,代码来源:experiment_controller.py

示例12: get_experiment_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def get_experiment_config(self, required_keys, experiment_name):        
        experiment_file_path = os.path.join(BASE_DIR, "config", "experiments", experiment_name) + ".yml"
        with open(experiment_file_path, 'r') as f:
            try:
                experiment_config_all = yaml.full_load(f)
            except yaml.YAMLError as exc:
                self.log.error("{0}: Failure loading experiment yaml {1}".format(
                    self.__class__.__name__, experiment_file_path), str(exc))
                sys.exit(1)
        if(ENV not in experiment_config_all.keys()):
            self.log.error("{0}: Cannot find experiment settings for {1} in {2}".format(
                self.__class__.__name__, ENV, experiment_file_path))
            sys.exit(1)

        experiment_config = experiment_config_all[ENV]
        for key in required_keys:
            if key not in experiment_config.keys():
                self.log.error("{0}: Value missing from {1}: {2}".format(
                    self.__class__.__name__, experiment_file_path, key))
                sys.exit(1)
        return experiment_config 
开发者ID:mitmedialab,项目名称:CivilServant,代码行数:23,代码来源:sticky_comment_experiment_controller.py

示例13: test_set_stylesheet

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def test_set_stylesheet(mock_reddit):
    r = mock_reddit.return_value
    with open(os.path.join(BASE_DIR,"tests", "fixture_data", "stylesheet_0" + ".json"), "r") as f:
        stylesheet = json.loads(f.read())
    r.get_stylesheet.return_value = stylesheet
    r.set_stylesheet.return_value = {"errors":[]}
    patch('praw.')

    experiment_name = "stylesheet_experiment_test"
    with open(os.path.join(BASE_DIR,"config", "experiments", experiment_name + ".yml"), "r") as f:
        experiment_config = yaml.full_load(f)['test']
    controller = StylesheetExperimentController(experiment_name, db_session, r, log)

    for condition in ['special', 'normal']:
        for arm in ["arm_0", "arm_1"]:
            assert (controller.experiment_settings['conditions'][condition]['arms'][arm] in stylesheet['stylesheet'].split("\n"))!=True

    for condition in ['special', 'normal']:
        for arm in ["arm_0", "arm_1"]:
            line_length = len(stylesheet['stylesheet'].split("\n"))
            result_lines = controller.set_stylesheet(condition, arm).split("\n")
            assert controller.experiment_settings['conditions'][condition]['arms'][arm] in result_lines
            assert len(result_lines) == line_length + 3 
开发者ID:mitmedialab,项目名称:CivilServant,代码行数:25,代码来源:test_stylesheet_experiment_controller.py

示例14: read_lint_config

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def read_lint_config(repo_path):
    # read .lintconfig.yml
    full_path = os.path.expanduser(repo_path)
    config_filepath = os.path.join(full_path, '.lintconfig.yml')
    acronyms = []
    abbreviations = []
    timeframes = []
    checks = []
    if os.path.isfile(config_filepath):
        with open(config_filepath) as f:
            config = yaml.full_load(f)
            acronyms = config.get('acronyms', acronyms)
            abbreviations = config.get('abbreviations', abbreviations)
            timeframes = config.get('timeframes', timeframes)
            checks = config.get('checks', checks)

    checks = _parse_checks(checks)
    return {'acronyms': acronyms, 'abbreviations': abbreviations, 'timeframes': timeframes, 'checks': checks} 
开发者ID:WarbyParker,项目名称:lookmlint,代码行数:20,代码来源:lookmlint.py

示例15: read_configuration

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import full_load [as 别名]
def read_configuration(sFileName):
    with open(sFileName) as yaml_file:
        return yaml.full_load(yaml_file) 
开发者ID:jeremiah-c-leary,项目名称:vhdl-style-guide,代码行数:5,代码来源:utils.py


注:本文中的yaml.full_load方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。