本文整理汇总了Python中parse.parse方法的典型用法代码示例。如果您正苦于以下问题:Python parse.parse方法的具体用法?Python parse.parse怎么用?Python parse.parse使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类parse
的用法示例。
在下文中一共展示了parse.parse方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_uninstall_script
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def build_uninstall_script():
#import utool as ut
from os.path import join
#import parse
pydir = 'C:/Python27'
uninstall_list = ut.glob(pydir, 'Remove*.exe')
cmd_list = []
for exefname in uninstall_list:
parse_result = parse.parse('{pypath}Remove{pkgname}.exe', exefname)
pkgname = parse_result['pkgname']
logfname = pkgname + '-wininst.log'
logfpath = join(pydir, logfname)
exefpath = join(pydir, exefname)
cmd = '"' + exefpath + '" -u "' + logfpath + '"'
cmd_list.append(cmd)
script_text = ('\n'.join(cmd_list))
print(script_text)
示例2: parse
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def parse(cls, shop, text_log):
'''
Parse from a text log with the format
[<Timestamp>] - SALE - PRODUCT: <product id> - PRICE: $<price> - NAME: <name> - DISCOUNT: <discount>%
to a SaleLog object
'''
def price(string):
return Decimal(string)
def isodate(string):
return delorean.parse(string)
FORMAT = ('[{timestamp:isodate}] - SALE - PRODUCT: {product:d} '
'- PRICE: ${price:price} - NAME: {name:D} '
'- DISCOUNT: {discount:d}%')
formats = {'price': price, 'isodate': isodate}
result = parse.parse(FORMAT, text_log, formats)
return cls(timestamp=result['timestamp'],
product_id=result['product'],
price=result['price'],
name=result['name'],
discount=result['discount'],
shop=shop)
示例3: get_name_texts_from_parent_folder
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def get_name_texts_from_parent_folder(gpath_list, img_dir, fmtkey=None):
"""
Input: gpath_list
Output: names based on the parent folder of each image
"""
#from os.path import commonprefix
relgpath_list = [relpath(gpath, img_dir) for gpath in gpath_list]
#_prefix = commonprefix(gpath_list)
#relgpath_list = [relpath(gpath, _prefix) for gpath in gpath_list]
_name_list = [dirname(relgpath) for relgpath in relgpath_list]
if fmtkey is not None:
#fmtkey = 'African Wild Dog: {name}'
import parse
parse_results = [parse.parse(fmtkey, name) for name in _name_list]
_name_list = [res['name'] if res is not None else name
for name, res in zip(_name_list, parse_results)]
name_list = list(map(normalize_name, _name_list))
return name_list
示例4: _read_special_reg_from_name
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def _read_special_reg_from_name(self, reg):
"""GDB does not return simple values for certain registers,
such as SSE-registers on x86.
This function tries to cover those cases by looking up an
expression to access the register, and the resulting format,
in the architecture description.
"""
ret, resp = self._sync_request(
["-data-evaluate-expression", "%s" %
self._arch.special_registers[reg]['gdb_expression']],
GDB_PROT_DONE)
fmt = self._arch.special_registers[reg]['format']
res = parse.parse(fmt, resp['payload']['value'])
if res is None:
self.log.critical(
"Unable to parse content of special register %s" % reg
)
raise Exception("Couldn't parse special register")
return list(res)
示例5: parse
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def parse(cls, text_log):
'''
Parse from a text log with the format
[<Timestamp>] - SALE - PRODUCT: <product id> - PRICE: $<price>
to a PriceLog object
'''
def price(string):
return Decimal(string)
def isodate(string):
return delorean.parse(string)
FORMAT = ('[{timestamp:isodate}] - SALE - PRODUCT: {product:d} - '
'PRICE: ${price:price}')
formats = {'price': price, 'isodate': isodate}
result = parse.parse(FORMAT, text_log, formats)
return cls(timestamp=result['timestamp'],
product_id=result['product'],
price=result['price'])
示例6: _spawnChildFromRn
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def _spawnChildFromRn(self, className, rn):
# TODO: Refactor.
moIter = getattr(self, className)
parsed = parse.parse(moIter._rnFormat, rn)
if parsed is None:
logging.debug('RN parsing failed, RN: {}, format: {}'.
format(rn, moIter._rnFormat))
# FIXME (2015-04-08, Praveen Kumar): Hack alert!
rn = rn.replace('[]', '[None]')
if rn.endswith('-'):
rn = rn + 'None'
parsed = parse.parse(moIter._rnFormat, rn)
identifierDict = parsed.named
orderedIdentifiers = [
t[0] for t in sorted(parsed.spans.items(),
key=operator.itemgetter(1))
]
identifierArgs = [
identifierDict[name] for name in orderedIdentifiers
]
return moIter(*identifierArgs)
示例7: _refreshLoginIfNeeded
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def _refreshLoginIfNeeded(self):
now = int(time.time())
if now + self.REFRESH_BEFORE > self._rootApi._login['nextRefreshBefore']:
logger.debug('arThread: Need to refresh Token')
refObj = self._rootApi.methods.LoginRefresh()
resp = refObj.GET()
# Process refresh response
if payloadFormat != 'xml' or resp.text[:5] != '<?xml':
logger.error('XML format of aaaLogin is only supported now')
return
doc = xmltodict.parse(resp.text)
if 'imdata' in doc:
if 'aaaLogin' in doc['imdata']:
root = self._rootApi
root._login = {}
lastLogin = int(time.time())
root._login['lastLoginTime'] = lastLogin
root._login['nextRefreshBefore'] = lastLogin - DELTA + \
int(doc['imdata']['aaaLogin']['@refreshTimeoutSeconds'])
else:
logger.error('arThread: response for aaaRefresh does not have required aaaLogin Tag')
else:
logger.error('arThread: response for aaaRefresh does not have required imdata Tag')
return
示例8: cleanup_snapshots
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def cleanup_snapshots(harn):
"""
Remove old snapshots according to configuration
Notes:
Influenced by 'num_keep' - the number of top ranking snapshots to
keep, and 'keep_freq' - the number of intermitent snapshots to keep
"""
snapshots = harn.prev_snapshots()
existing_epochs = sorted([
int(parse.parse('{}_epoch_{num:d}.pt', path).named['num'])
for path in snapshots
])
num_keep_recent = harn.preferences['num_keep']
num_keep_best = harn.preferences['num_keep']
keep_freq = harn.preferences['keep_freq']
epoch_to_fpath = dict(zip(existing_epochs, snapshots))
to_remove = harn._epochs_to_remove(existing_epochs, num_keep_recent,
num_keep_best, keep_freq)
for fpath in ub.take(epoch_to_fpath, to_remove):
ub.delete(fpath)
示例9: find_pretrained
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def find_pretrained(self):
import glob
import parse
fname_fmt = self.fname_fmtstr + '.cPkl'
task_clf_candidates = ut.ddict(list)
globstr = self.fname_parts[0] + '.*.cPkl'
for fpath in glob.iglob(join(self.dpath, globstr)):
fname = basename(fpath)
result = parse.parse(fname_fmt, fname)
if result:
task_key = result.named['task_key']
task_clf_candidates[task_key].append(fpath)
return task_clf_candidates
示例10: run_command
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def run_command(cmd, *args, **kwargs):
"""
Take an input command and run it, handling exceptions and error codes and returning
its stdout and stderr.
:param cmd: The list of command and arguments.
:type cmd: list
:returns: A 2-tuple of the output and error from the command
:rtype: Tuple[str, str]
:raises: exceptions.PipenvCmdError
"""
from pipenv.vendor import delegator
from ._compat import decode_for_output
from .cmdparse import Script
catch_exceptions = kwargs.pop("catch_exceptions", True)
if isinstance(cmd, (six.string_types, list, tuple)):
cmd = Script.parse(cmd)
if not isinstance(cmd, Script):
raise TypeError("Command input must be a string, list or tuple")
if "env" not in kwargs:
kwargs["env"] = os.environ.copy()
kwargs["env"]["PYTHONIOENCODING"] = "UTF-8"
try:
cmd_string = cmd.cmdify()
except TypeError:
click_echo("Error turning command into string: {0}".format(cmd), err=True)
sys.exit(1)
if environments.is_verbose():
click_echo("Running command: $ {0}".format(cmd_string, err=True))
c = delegator.run(cmd_string, *args, **kwargs)
return_code = c.return_code
if environments.is_verbose():
click_echo("Command output: {0}".format(
crayons.blue(decode_for_output(c.out))
), err=True)
if not c.ok and catch_exceptions:
raise PipenvCmdError(cmd_string, c.out, c.err, return_code)
return c
示例11: proper_case
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def proper_case(package_name):
"""Properly case project name from pypi.org."""
# Hit the simple API.
r = _get_requests_session().get(
"https://pypi.org/pypi/{0}/json".format(package_name), timeout=0.3, stream=True
)
if not r.ok:
raise IOError(
"Unable to find package {0} in PyPI repository.".format(package_name)
)
r = parse.parse("https://pypi.org/pypi/{name}/json", r.url)
good_name = r["name"]
return good_name
示例12: parse_errors
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def parse_errors(err, directory, asg, **kwargs):
if not isinstance(err, str):
raise TypeError('\'err\' parameter')
if not isinstance(directory, Path):
directory = Path(directory)
variant_dir = kwargs.pop('variant_dir', None)
if variant_dir:
variant_dir = directory/variant_dir
else:
variant_dir = directory
src_dir = kwargs.pop('src_dir', None)
if src_dir:
src_dir = directory/src_dir
else:
src_dir = directory
indent = kwargs.pop('indent', 0)
src_dir = str(src_dir.abspath()) + os.sep
variant_dir = str(variant_dir.relpath(directory))
if variant_dir == '.':
variant_dir = ''
else:
variant_dir += os.sep
wrappers = dict()
for line in err.splitlines():
parsed = parse.parse(variant_dir+'{filename}:{row}:{column}:{message}', line)
if parsed:
try:
row = int(parsed['row'])
node = src_dir + parsed['filename']
if node in asg:
if node not in wrappers:
wrappers[node] = [row]
else:
wrappers[node].append(row)
except:
pass
return wrappers
示例13: from_row
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def from_row(cls, row):
timestamp_str, shop, product_id, name, raw_price, discount_str = row
timestamp = delorean.parse(timestamp_str)
discount = parse.parse('{:d}%', discount_str)[0]
# Round to remove possible rounding errors in Excel
price = round(Decimal(raw_price), 2)
return cls(timestamp=timestamp, product_id=product_id,
price=price, name=name, discount=discount,
shop=shop)
示例14: parse_group_name
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def parse_group_name(self, group):
"""Parses the group name for the name of the proid.
"""
match = parse.parse(self.group_pattern, group)
if match is None:
return None
return match[0]
示例15: POST
# 需要导入模块: import parse [as 别名]
# 或者: from parse import parse [as 别名]
def POST(self, format=None, **kwargs):
resp = super(LoginMethod, self).POST(format=format, **kwargs)
if resp is None or resp.status_code != requests.codes.ok:
logger.debug('Login failed!')
return resp
if payloadFormat != 'xml' or resp.text[:5] != '<?xml':
logger.error('XML format of aaaLogin is only supported now')
return resp
doc = xmltodict.parse(resp.text)
if 'imdata' in doc:
if 'aaaLogin' in doc['imdata']:
root = self._rootApi()
root._login = {}
root._login['version'] = doc['imdata']['aaaLogin']['@version']
root._login['userName'] = doc['imdata']['aaaLogin']['@userName']
lastLogin = int(time.time())
root._login['lastLoginTime'] = lastLogin
root._login['nextRefreshBefore'] = lastLogin - DELTA + \
int(doc['imdata']['aaaLogin']['@refreshTimeoutSeconds'])
logger.debug(root._login)
if root._autoRefresh:
arThread = AutoRefreshThread(root)
root._autoRefreshThread = arThread
arThread.daemon = True
arThread.start()
return resp