本文整理汇总了Python中string.Formatter.format方法的典型用法代码示例。如果您正苦于以下问题:Python Formatter.format方法的具体用法?Python Formatter.format怎么用?Python Formatter.format使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类string.Formatter
的用法示例。
在下文中一共展示了Formatter.format方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: select
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def select(self,type='VAV',subtype = ['RM STPT DIAL','ROOM TEMP'], floor = 0,nexp='', pattern ='{i}',cond = 'cmax(x,7)',maxn = 10, dtfilter = ''):
env = self._genv()
env.init()
l = env.getSensorsByType(type)
lname = []
for it in l:
k = it.split(':')
if floor != 0:
fl = int(k[0].split('.')[1])
if fl != floor:
continue
if nexp != '':
sname = k[0].split('.')[3]
if not fnmatch.fnmatch(sname,nexp):
continue
if k[1] in subtype:
lname.append((it,env.getSensorId(it)))
ltemp = sorted(lname,key=itemgetter(0))[:maxn]
filt = ''
i = 0
f = Formatter()
l = "{{%s}}"
f.format(l)
ns = ''
exp = []
i,m =0,len(ltemp)
loopi=0
while i < m:
h = f.parse(pattern)
for a,b,c,d in h :
ns += a
if b is not None :
ns += '{' + str(eval(b)) + '}'
i = eval(b)
loopi = max(i,loopi)
if cond != '':
ns += '.apply(lambda x:' + cond + ')'
if loopi < m-1:
ns += '; '
i = loopi + 1
cs = self.getSeries(ltemp,dtfilter)
re = self.getExpression(ltemp,ns, cs)
series = []
for name ,c in re:
dataserie = defaultdict()
json_s = c[['stime','svalue']].to_json(orient='values')
dataserie['name']=name
dataserie['data']=json_s
series.append(dataserie)
return series
示例2: format
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def format(self, format_string, *args, **kwargs):
def escape_envvar(matchobj):
value = (x for x in matchobj.groups() if x is not None).next()
return "${{%s}}" % value
format_string_ = re.sub(self.ENV_VAR_REGEX, escape_envvar, format_string)
return Formatter.format(self, format_string_, *args, **kwargs)
示例3: strfdelta
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def strfdelta(tdelta, fmt):
""" Get a string from a timedelta.
"""
f, d = Formatter(), {}
l = {'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
k = list(map(lambda x: x[1], list(f.parse(fmt))))
rem = int(tdelta.total_seconds())
for i in ('D', 'H', 'M', 'S'):
if i in k and i in l.keys():
d[i], rem = divmod(rem, l[i])
return f.format(fmt, **d)
示例4: TableCell
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
class TableCell():
def __init__(self, content=None):
self.content = content
self.fmtr = Formatter()
def __repr__(self):
return self.display()
def display(self):
""" type dependent string formatting """
if isinstance(self.content, UFloat):
return "{}".format(self.fmtr.format("{0:.1uS}", self.content))
elif isinstance(self.content, int):
return "{}".format(self.fmtr.format("{0:.0f}", self.content))
elif isinstance(self.content, float):
return "{}".format(self.fmtr.format("{0:.3f}", self.content))
elif isinstance(self.content, basestring):
return self.content
elif self.content is None:
return "None"
else:
return str(self.content)
示例5: SimpleBar
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
class SimpleBar(object):
"""A minimal progress bar widget for stdout.
Displays a custom message to sys.stdout, and updates it in-place on demand.
"""
def __init__(self, message_str=None, max_width=80):
"""Create a SimpleBar with an optional message string.
Args:
message_str(str): An optional format string that is displayed and formatted
in every update operation.
max_width(int): The maximum width of the progress bar, message and all.
"""
self.formatter = Formatter()
if message_str:
self.message_str = message_str
self.max_width = max_width
def update_args(self, *args):
"""Display the appropriately updated progress message.
Args:
args: Formatter-style arguments for the format string.
"""
self.__restart_line()
print self.__pad_string(self.formatter.format(self.message_str, *args),
self.max_width),
def update(self, string, *args):
"""Update progress message and display with appropriate updates.
Args:
string (str): The format string for the message to be displayed.
args (optional arguments): Formatter-style arguments for the format string.
"""
self.message_str = string
self.update_args(*args)
def __restart_line(self):
"""Move cursor to the start of the current line immediately.
"""
sys.stdout.write('\r')
sys.stdout.flush()
def __pad_string(self, s, length):
"""Pad a string with trailing spaces to the given length.
"""
return s.ljust(length)
示例6: strfdelta
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def strfdelta(tdelta, fmt=None):
from string import Formatter
if not fmt:
# The standard, most human readable format.
fmt = "{D} days {H:02} hours {M:02} minutes {S:02} seconds"
if tdelta == timedelta():
return "0 minutes"
formatter = Formatter()
return_map = {}
div_by_map = {'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
keys = map(lambda x: x[1], list(formatter.parse(fmt)))
remainder = int(tdelta.total_seconds())
for unit in ('D', 'H', 'M', 'S'):
if unit in keys and unit in div_by_map.keys():
return_map[unit], remainder = divmod(remainder, div_by_map[unit])
return formatter.format(fmt, **return_map)
示例7: strfdelta
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def strfdelta(tdelta, fmt='{D:02}d {H:02}h {M:02}m {S:02}s', inputtype='timedelta'):
"""Convert a datetime.timedelta object or a regular number to a custom-
formatted string, just like the stftime() method does for datetime.datetime
objects.
The fmt argument allows custom formatting to be specified. Fields can
include seconds, minutes, hours, days, and weeks. Each field is optional.
Some examples:
'{D:02}d {H:02}h {M:02}m {S:02}s' --> '05d 08h 04m 02s' (default)
'{W}w {D}d {H}:{M:02}:{S:02}' --> '4w 5d 8:04:02'
'{D:2}d {H:2}:{M:02}:{S:02}' --> ' 5d 8:04:02'
'{H}h {S}s' --> '72h 800s'
The inputtype argument allows tdelta to be a regular number instead of the
default, which is a datetime.timedelta object. Valid inputtype strings:
's', 'seconds',
'm', 'minutes',
'h', 'hours',
'd', 'days',
'w', 'weeks'
"""
# Convert tdelta to integer seconds.
if inputtype == 'timedelta':
remainder = int(tdelta.total_seconds())
elif inputtype in ['s', 'seconds']:
remainder = int(tdelta)
elif inputtype in ['m', 'minutes']:
remainder = int(tdelta)*60
elif inputtype in ['h', 'hours']:
remainder = int(tdelta)*3600
elif inputtype in ['d', 'days']:
remainder = int(tdelta)*86400
elif inputtype in ['w', 'weeks']:
remainder = int(tdelta)*604800
f = Formatter()
desired_fields = [field_tuple[1] for field_tuple in f.parse(fmt)]
possible_fields = ('W', 'D', 'H', 'M', 'S')
constants = {'W': 604800, 'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
values = {}
for field in possible_fields:
if field in desired_fields and field in constants:
values[field], remainder = divmod(remainder, constants[field])
return f.format(fmt, **values)
示例8: strfdelta
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def strfdelta(tsec, format_str="P", format_no_day="PT{H}H{M}M{S}S", format_zero="PT0S"):
"""Formatting the time duration.
Duration ISO8601 format (PnYnMnDTnHnMnS): http://en.wikipedia.org/wiki/ISO_8601
Choosing the format P[nD]TnHnMnS where days is the total number of days (if not 0), 0 values may be omitted,
0 duration is PT0S
:param tsec: float, number of seconds
:param format_str: Format string, ISO 8601 is "P{D}DT{H}H{M}M{S}S". Default is a format string "P": will
use ISO 8601 but skip elements that have 0 value, e.g. P1H7S instead of P1H0M7S
:param format_no_day: Format string, ISO 8601, default "PT{H}H{M}M{S}S"
:param format_zero: format for when tsec is 0 or None, default "PT0S"
:return: Formatted time duration
"""
if not tsec:
# 0 or None
return format_zero
f = Formatter()
d = {}
l = {'D': 86400, 'H': 3600, 'M': 60, 'S': 1}
rem = long(tsec)
if format_str == "P":
# variable format
if 0 < tsec < 86400:
format_str = "PT"
for i in ('D', 'H', 'M', 'S'):
if i in l.keys():
d[i], rem = divmod(rem, l[i])
if d[i] != 0:
format_str = "%s{%s}%s" % (format_str, i, i)
else:
if 0 < tsec < 86400:
format_str = format_no_day
k = map(lambda x: x[1], list(f.parse(format_str)))
for i in ('D', 'H', 'M', 'S'):
if i in k and i in l.keys():
d[i], rem = divmod(rem, l[i])
return f.format(format_str, **d)
示例9: format
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def format(self, format_string, *args, **kwargs):
def escape_envvar(matchobj):
value = (x for x in matchobj.groups() if x is not None).next()
return "${{%s}}" % value
format_string_ = re.sub(self.ENV_VAR_REGEX, escape_envvar, format_string)
# for recursive formatting, where a field has a value we want to expand,
# add kwargs to namespace, so format_field can use them...
if kwargs:
prev_namespace = self.namespace
self.namespace = dict(prev_namespace)
self.namespace.update(kwargs)
else:
prev_namespace = None
try:
return Formatter.format(self, format_string_, *args, **kwargs)
finally:
if prev_namespace is not None:
self.namespace = prev_namespace
示例10: CpuUsage
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
class CpuUsage(IntervalModule):
"""
Shows CPU usage.
The first output will be inacurate.
Linux only
.. rubric:: Available formatters
* `{usage}` — usage average of all cores
* `{usage_cpu*}` — usage of one specific core. replace "*" by core number starting at 0
* `{usage_all}` — usage of all cores separate. usess natsort when available(relevant for more than 10 cores)
"""
format = "{usage:02}%"
format_all = "{core}:{usage:02}%"
exclude_average = False
interval = 1
color = None
settings = (
("format", "format string."),
("format_all", ("format string used for {usage_all} per core. "
"Available formaters are {core} and {usage}. ")),
("exclude_average", ("If True usage average of all cores will "
"not be in format_all.")),
("color", "HTML color code #RRGGBB")
)
def init(self):
self.prev_total = defaultdict(int)
self.prev_busy = defaultdict(int)
self.formatter = Formatter()
def get_cpu_timings(self):
"""
reads and parses /proc/stat
returns dictionary with all available cores including global average
"""
timings = {}
with open('/proc/stat', 'r') as file_obj:
for line in file_obj:
if 'cpu' in line:
line = line.strip().split()
timings[line[0]] = [int(x) for x in line[1:]]
return timings
def calculate_usage(self, cpu, total, busy):
"""
calculates usage
"""
diff_total = total - self.prev_total[cpu]
diff_busy = busy - self.prev_busy[cpu]
self.prev_total[cpu] = total
self.prev_busy[cpu] = busy
if diff_total == 0:
return 0
else:
return int(diff_busy / diff_total * 100)
def gen_format_all(self, usage):
"""
generates string for format all
"""
format_string = " "
core_strings = []
for core, usage in usage.items():
if core == 'usage_cpu' and self.exclude_average:
continue
elif core == 'usage':
continue
core = core.replace('usage_', '')
string = self.formatter.format(format_string=self.format_all,
core=core,
usage=usage)
core_strings.append(string)
core_strings = sorted(core_strings)
return format_string.join(core_strings)
def get_usage(self):
"""
parses /proc/stat and calcualtes total and busy time
(more specific USER_HZ see man 5 proc for further informations )
"""
usage = {}
for cpu, timings in self.get_cpu_timings().items():
cpu_total = sum(timings)
del timings[3:5]
cpu_busy = sum(timings)
cpu_usage = self.calculate_usage(cpu, cpu_total, cpu_busy)
usage['usage_' + cpu] = cpu_usage
#.........这里部分代码省略.........
示例11: format
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def format(self, format_string, *args, **kwargs):
self.caller = sys._getframe(self.level)
return Formatter.format(self, format_string, *args, **kwargs)
示例12: compute_one_task
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
def compute_one_task(self, itask, task):
"""
Run the algorithm once, using the parameters specified by `task`,
which is the `itask` iteration
Parameters
----------
itask : int
the integer index of this task
task : tuple
a tuple of values representing this task value
"""
# if you are the pool's root, write out the temporary parameter file
this_config = None
if self.workers.subcomm.rank == 0:
# initialize a temporary file
with tempfile.NamedTemporaryFile(delete=False) as ff:
this_config = ff.name
logger.debug("creating temporary file: %s" %this_config)
# key/values for this task
if len(self.task_dims) == 1:
possible_kwargs = {self.task_dims[0] : task}
else:
possible_kwargs = dict(zip(self.task_dims, task))
# any extra key/value pairs for this tasks
if self.extras is not None:
for k in self.extras:
possible_kwargs[k] = self.extras[k][itask]
# use custom formatter that only formats the possible keys, ignoring other
# occurences of curly brackets
formatter = Formatter()
formatter.parse = lambda l: SafeStringParse(formatter, l, list(possible_kwargs))
kwargs = [kw for _, kw, _, _ in formatter.parse(self.template) if kw]
# do the string formatting if the key is present in template
valid = {k:possible_kwargs[k] for k in possible_kwargs if k in kwargs}
ff.write(formatter.format(self.template, **valid).encode())
# bcast the file name to all in the worker pool
this_config = self.workers.subcomm.bcast(this_config, root=0)
# configuration file passed via -c
params, extra = ReadConfigFile(open(this_config, 'r').read(), self.algorithm_class.schema)
# output is required
output = getattr(extra, 'output', None)
if output is None:
raise ValueError("argument `output` is required in config file")
# initialize the algorithm and run
alg = self.algorithm_class(**vars(params))
result = alg.run()
alg.save(output, result)
# remove temporary files
if self.workers.subcomm.rank == 0:
if os.path.exists(this_config):
logger.debug("removing temporary file: %s" %this_config)
os.remove(this_config)
return 0
示例13: CpuUsage
# 需要导入模块: from string import Formatter [as 别名]
# 或者: from string.Formatter import format [as 别名]
class CpuUsage(IntervalModule, ColorRangeModule):
"""
Shows CPU usage.
The first output will be inacurate.
Linux only
Requires the PyPI package 'colour'.
.. rubric:: Available formatters
* `{usage}` — usage average of all cores
* `{usage_cpu*}` — usage of one specific core. replace "*" by core number starting at 0
* `{usage_all}` — usage of all cores separate. usess natsort when available(relevant for more than 10 cores)
"""
format = "{usage:02}%"
format_all = "{core}:{usage:02}%"
exclude_average = False
interval = 1
color = None
dynamic_color = False
upper_limit = 100
settings = (
("format", "format string."),
("format_all", ("format string used for {usage_all} per core. "
"Available formaters are {core} and {usage}. ")),
("exclude_average", ("If True usage average of all cores will "
"not be in format_all.")),
("color", "HTML color code #RRGGBB"),
("dynamic_color", "Set color dynamically based on CPU usage. Note: this overrides color_up"),
("start_color", "Hex or English name for start of color range, eg '#00FF00' or 'green'"),
("end_color", "Hex or English name for end of color range, eg '#FF0000' or 'red'")
)
def init(self):
self.prev_total = defaultdict(int)
self.prev_busy = defaultdict(int)
self.formatter = Formatter()
self.key = re.findall('usage_cpu\d+', self.format)
if len(self.key) == 1:
self.key = self.key[0]
else:
self.key = 'usage_cpu'
if not self.color:
self.color = '#FFFFFF'
if not self.dynamic_color:
self.start_color = self.color
self.end_color = self.color
self.colors = self.get_hex_color_range(self.start_color, self.end_color, int(self.upper_limit))
def get_cpu_timings(self):
"""
reads and parses /proc/stat
returns dictionary with all available cores including global average
"""
timings = {}
with open('/proc/stat', 'r') as file_obj:
for line in file_obj:
if 'cpu' in line:
line = line.strip().split()
timings[line[0]] = [int(x) for x in line[1:]]
return timings
def calculate_usage(self, cpu, total, busy):
"""
calculates usage
"""
diff_total = total - self.prev_total[cpu]
diff_busy = busy - self.prev_busy[cpu]
self.prev_total[cpu] = total
self.prev_busy[cpu] = busy
if diff_total == 0:
return 0
else:
return int(diff_busy / diff_total * 100)
def gen_format_all(self, usage):
"""
generates string for format all
"""
format_string = " "
core_strings = []
for core, usage in usage.items():
if core == 'usage_cpu' and self.exclude_average:
continue
elif core == 'usage':
continue
core = core.replace('usage_', '')
string = self.formatter.format(format_string=self.format_all,
core=core,
usage=usage)
core_strings.append(string)
#.........这里部分代码省略.........