當前位置: 首頁>>代碼示例>>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;未經允許,請勿轉載。