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


Python yaml.SafeLoader方法代码示例

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


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

示例1: __read_settings

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def __read_settings(self, yaml_file):
        if yaml_file is None:
            yaml_file = os.path.join(ciftify.config.find_ciftify_global(),
                    'ciftify_workflow_settings.yaml')
        if not os.path.exists(yaml_file):
            logger.critical("Settings yaml file {} does not exist"
                "".format(yaml_file))
            sys.exit(1)

        try:
            with open(yaml_file, 'r') as yaml_stream:
                config = yaml.load(yaml_stream, Loader=yaml.SafeLoader)
        except:
            logger.critical("Cannot read yaml config file {}, check formatting."
                    "".format(yaml_file))
            sys.exit(1)

        return config 
开发者ID:edickie,项目名称:ciftify,代码行数:20,代码来源:utils.py

示例2: __init__

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def __init__(self, filename, requests_and_responses=False):
        self._filename = filename
        self._requests_and_responses = requests_and_responses
        json_ext = '.json'
        yaml_ext = '.yaml'
        if filename[-len(json_ext):] == json_ext:
            self._scan = json.loads(open(filename).read().decode('utf-8-sig'), object_pairs_hook=UnsortableOrderedDict)
        elif filename[-len(yaml_ext):] == yaml_ext:
            self._scan = yaml_load(open(filename).read(), yaml.SafeLoader, UnsortableOrderedDict)
        else:
            # xml
            #self._xml = etree.parse(filename)
            etree_parser = etree.XMLParser(huge_tree=True)
            self._xml = etree.parse(filename, parser=etree_parser)
            root = self._xml.getroot()
            if root.tag == 'Sessions':
                self._webinspect_import()
            elif root.tag == 'issues':
                self._burp_import()
            elif root.tag == 'items':
                self._burp_items_import()
            else:
                raise Exception('Unknown scan format!') 
开发者ID:hvqzao,项目名称:report-ng,代码行数:25,代码来源:scan.py

示例3: __read_mode

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def __read_mode(self, mode):
        logger = logging.getLogger(__name__)
        ciftify_data = config.find_ciftify_global()
        qc_settings = os.path.join(ciftify_data, 'qc_modes.yaml')
        try:
            with open(qc_settings, 'r') as qc_stream:
                qc_modes = yaml.load(qc_stream, Loader=yaml.SafeLoader)
        except:
            logger.error("Cannot read qc_modes file: {}".format(qc_settings))
            sys.exit(1)
        try:
            settings = qc_modes[mode]
        except KeyError:
            logger.error("qc_modes file {} does not define mode {}"
                    "".format(qc_settings, mode))
            sys.exit(1)
        return settings 
开发者ID:edickie,项目名称:ciftify,代码行数:19,代码来源:qc_config.py

示例4: importyaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def importyaml(connection,metadata,sourcePath):
    eveGraphics = Table('eveGraphics',metadata)
    print "Importing Graphics"
    print "opening Yaml"
    with open(os.path.join(sourcePath,'fsd','graphicIDs.yaml'),'r') as yamlstream:
        print "importing"
        trans = connection.begin()
        graphics=load(yamlstream,Loader=SafeLoader)
        print "Yaml Processed into memory"
        for graphic in graphics:
            connection.execute(eveGraphics.insert(),
                            graphicID=graphic,
                            sofFactionName=graphics[graphic].get('sofFactionName',''),
                            graphicFile=graphics[graphic].get('graphicFile',''),
                            sofHullName=graphics[graphic].get('sofHullName',''),
                            sofRaceName=graphics[graphic].get('sofRaceName',''),
                            description=graphics[graphic].get('description',''))
    trans.commit() 
开发者ID:fuzzysteve,项目名称:yamlloader,代码行数:20,代码来源:graphics.py

示例5: importyaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def importyaml(connection,metadata,sourcePath,language='en'):
    invGroups = Table('invGroups',metadata)
    trnTranslations = Table('trnTranslations',metadata)
    print "Importing Groups"
    print "opening Yaml"
    with open(os.path.join(sourcePath,'fsd','groupIDs.yaml'),'r') as yamlstream:
        trans = connection.begin()
        groupids=load(yamlstream,Loader=SafeLoader)
        print "Yaml Processed into memory"
        for groupid in groupids:
            connection.execute(invGroups.insert(),
                            groupID=groupid,
                            categoryID=groupids[groupid].get('categoryID',0),
                            groupName=groupids[groupid].get('name',{}).get(language,'').decode('utf-8'),
                            iconID=groupids[groupid].get('iconID'),
                            useBasePrice=groupids[groupid].get('useBasePrice'),
                            anchored=groupids[groupid].get('anchored',0),
                            anchorable=groupids[groupid].get('anchorable',0),
                            fittableNonSingleton=groupids[groupid].get('fittableNonSingleton',0),
                            published=groupids[groupid].get('published',0))
            if (groupids[groupid].has_key('name')):
                for lang in groupids[groupid]['name']:
                    connection.execute(trnTranslations.insert(),tcID=7,keyID=groupid,languageID=lang,text=groupids[groupid]['name'][lang].decode('utf-8'));
    trans.commit() 
开发者ID:fuzzysteve,项目名称:yamlloader,代码行数:26,代码来源:groups.py

示例6: importyaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def importyaml(connection,metadata,sourcePath,language='en'):
    print "Importing dogma attribute categories"
    dgmAttributeCategories = Table('dgmAttributeCategories',metadata)
    
    print "opening Yaml"
        
    trans = connection.begin()
    with open(os.path.join(sourcePath,'fsd','dogmaAttributeCategories.yaml'),'r') as yamlstream:
        print "importing"
        dogmaAttributeCategories=load(yamlstream,Loader=SafeLoader)
        print "Yaml Processed into memory"
        for dogmaAttributeCategoryID in dogmaAttributeCategories:
          attribute = dogmaAttributeCategories[dogmaAttributeCategoryID]
          connection.execute(dgmAttributeCategories.insert(),
                             categoryID=dogmaAttributeCategoryID,
                             categoryName=attribute['name'],
                             categoryDescription=attribute['description']
                )
    trans.commit() 
开发者ID:fuzzysteve,项目名称:yamlloader,代码行数:21,代码来源:dogmaAttributeCategories.py

示例7: importyaml

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def importyaml(connection,metadata,sourcePath):

    print "Importing BSD Tables"

    files=glob.glob(os.path.join(sourcePath,'bsd','*.yaml'))
    for file in files:
        head, tail = os.path.split(file)
        tablename=tail.split('.')[0]
        print tablename
        tablevar = Table(tablename,metadata)
        print "Importing {}".format(file)
        print "Opening Yaml"
        trans = connection.begin()
        with open(file,'r') as yamlstream:
            rows=load(yamlstream,Loader=SafeLoader)
            print "Yaml Processed into memory"
            for row in rows:
                connection.execute(tablevar.insert().values(row))
        trans.commit() 
开发者ID:fuzzysteve,项目名称:yamlloader,代码行数:21,代码来源:bsdTables.py

示例8: make_loader

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def make_loader(*tags_to_remove: str) -> Type[yaml.SafeLoader]:
    """Create a YAML loader, that doesn't parse specific tokens into Python objects."""
    cls: Type[yaml.SafeLoader] = type("YAMLLoader", (SafeLoader,), {})
    cls.yaml_implicit_resolvers = {
        key: [(tag, regexp) for tag, regexp in mapping if tag not in tags_to_remove]
        for key, mapping in cls.yaml_implicit_resolvers.copy().items()
    }

    # Fix pyyaml scientific notation parse bug
    # See PR: https://github.com/yaml/pyyaml/pull/174 for upstream fix
    cls.add_implicit_resolver(  # type: ignore
        "tag:yaml.org,2002:float",
        re.compile(
            r"""^(?:[-+]?(?:[0-9][0-9_]*)\.[0-9_]*(?:[eE][-+]?[0-9]+)?
                       |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
                       |\.[0-9_]+(?:[eE][-+]?[0-9]+)?
                       |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*
                       |[-+]?\.(?:inf|Inf|INF)
                       |\.(?:nan|NaN|NAN))$""",
            re.X,
        ),
        list("-+0123456789."),
    )

    return cls 
开发者ID:kiwicom,项目名称:schemathesis,代码行数:27,代码来源:utils.py

示例9: parse_args

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def parse_args(parser):
    args = parser.parse_args()
    if args.config_file:
        loader = yaml.SafeLoader
        loader.add_implicit_resolver(
            u'tag:yaml.org,2002:float',
            re.compile(u'''^(?:
        [-+]?(?:[0-9][0-9_]*)\\.[0-9_]*(?:[eE][-+]?[0-9]+)?
        |[-+]?(?:[0-9][0-9_]*)(?:[eE][-+]?[0-9]+)
        |\\.[0-9_]+(?:[eE][-+][0-9]+)?
        |[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\\.[0-9_]*
        |[-+]?\\.(?:inf|Inf|INF)
        |\\.(?:nan|NaN|NAN))$''', re.X),
            list(u'-+0123456789.'))
        data = yaml.load(args.config_file, Loader=loader)
        delattr(args, 'config_file')
        arg_dict = args.__dict__
        # print(len(list(arg_dict.keys())))
        # print(len(list(data.keys())))
        for key, value in arg_dict.items():
            default_arg = parser.get_default(key)
            if arg_dict[key] == default_arg and key in data:
                arg_dict[key] = data[key]
    return args 
开发者ID:walsvid,项目名称:Pixel2MeshPlusPlus,代码行数:26,代码来源:config.py

示例10: Deserializer

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def Deserializer(stream_or_string, **options):
    """
    Deserialize a stream or string of YAML data.
    """
    if isinstance(stream_or_string, bytes):
        stream_or_string = stream_or_string.decode('utf-8')
    if isinstance(stream_or_string, six.string_types):
        stream = StringIO(stream_or_string)
    else:
        stream = stream_or_string
    try:
        for obj in PythonDeserializer(yaml.load(stream, Loader=SafeLoader), **options):
            yield obj
    except GeneratorExit:
        raise
    except Exception as e:
        # Map to deserializer error
        six.reraise(DeserializationError, DeserializationError(e), sys.exc_info()[2]) 
开发者ID:lanbing510,项目名称:GTDWeb,代码行数:20,代码来源:pyyaml.py

示例11: GUI

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def GUI():
    wx_app = wx.App(redirect=True) # redirect in wxpython 3.0 defaults to False
    #wx_app = wx.App(redirect=False)
    #YamledWindow(content='../workbench/x.yaml')
    #YamledWindow(content='../workbench/y.yaml')
    #YamledWindow(content='../workbench/_yamled_dies.yaml')
    #YamledWindow(content='../workbench/yamled/sample-1.yaml')
    #YamledWindow(content='../workbench/yamled/pt.yaml')
    #YamledWindow(content=yaml_load(open('../workbench/yamled/burp-state-1-report.yaml').read(), yaml.SafeLoader, UnsortableOrderedDict))
    #YamledWindow(content='../workbench/yamled/asdf.yaml')
    #YamledWindow(content='../workbench/yamled/asdfgh.yaml')
    #YamledWindow(content='../workbench/yamled/burp-state-1-report.yaml')
    #YamledWindow(content='../workbench/yamled/_export_webinspect.yaml')
    #YamledWindow(content='../workbench/yamled/midsized.yaml')
    YamledWindow()
    #YamledWindow(content='../workbench/xss-2-intruder-items.yaml')
    wx_app.MainLoop() 
开发者ID:hvqzao,项目名称:report-ng,代码行数:19,代码来源:yamled.py

示例12: _input_json_from_file

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def _input_json_from_file(path):
        try:
            with open(path, encoding="utf-8") as file:
                return load(file)
        except IOError as e:
            raise RuntimeError(
                "File '{}' cannot be opened:\n{}".format(path, e)
            )
        except ValueError as e:
            try:
                with open(path, encoding="utf-8") as file:
                    return load_yaml(file, Loader=SafeLoader)
            except ValueError:
                raise RuntimeError(
                    "File '{}' is not valid JSON or YAML:\n{}".format(path, e)
                ) 
开发者ID:asyrjasalo,项目名称:RESTinstance,代码行数:18,代码来源:__init__.py

示例13: gtfobins

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def gtfobins(bin_name: str):
    """Search binaries from GTFOBins within command line

    Arguments:
        bin_name {[type]} -- Name of the binary to get info about

    """

    bins = get_bins()

    if bin_name in bins:
        r = requests.get(RAW_URL.format(bin_name)).text
        data = list(yaml.load_all(r, Loader=yaml.SafeLoader))[0]

        parse(data)
    else:
        print(colors("[!] Binary not found on GTFObins: ", 91)) 
开发者ID:mzfr,项目名称:gtfo,代码行数:19,代码来源:gtfobins.py

示例14: lolbas

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def lolbas(name: str):
    """Search binaries from LOLBAS within command line

    Arguments:
        name {[type]} -- Name of the exe to get info about

    Keyword Arguments:
        cmd {str} -- get only the code section (default: {False})
    """

    exes = get_exe()
    if name in exes.keys():
        url = RAW_URL + exes[name] + '.md'
        r = requests.get(url).text
        data = list(yaml.load_all(r, Loader=yaml.SafeLoader))[0]
        parse(data)
    else:
        print(colors("[!] Binary not found on LOLBAS", 91))
        #TODO: Match user input and make suggestion for search
        print(colors("[!] Make sure to provide name with proper extension", 91)) 
开发者ID:mzfr,项目名称:gtfo,代码行数:22,代码来源:lolbas.py

示例15: read

# 需要导入模块: import yaml [as 别名]
# 或者: from yaml import SafeLoader [as 别名]
def read(self, config_file):
        cfg = None
        if isinstance(config_file, dict):
            cfg = config_file.get('atomicpuppy')
        elif isinstance(config_file, str):
            with open(config_file) as file:
                cfg = yaml.load(file, yaml.SafeLoader).get('atomicpuppy')
        else:
            cfg = yaml.load(config_file, yaml.SafeLoader).get('atomicpuppy')


        streams = []
        instance = cfg.get('instance') or platform.node()
        for stream in cfg.get("streams"):
            streams.append(stream)
        ctr = self._make_counter(cfg, instance)
        return SubscriptionConfig(streams=streams,
                                  counter_factory=ctr,
                                  instance_name=instance,
                                  host=cfg.get("host") or 'localhost',
                                  port=cfg.get("port") or 2113,
                                  timeout=cfg.get("timeout") or 20,
                                  page_size=cfg.get("page_size") or 20) 
开发者ID:madedotcom,项目名称:atomicpuppy,代码行数:25,代码来源:atomicpuppy.py


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