python条件字符串_将Python字符串解释为条件语句?

这应该是您想要的:from __future__ import print_function

import ast

import operator

import sys

OPERATORS = {

'

'<=': operator.le,

'>': operator.gt,

'>=': operator.ge,

'==': operator.eq,

'!=': operator.ne,

# 'in' is using a lambda because of the opposite operator order

# 'in': (lambda item, container: operator.contains(container, item),

'in': (lambda item, container: item in container),

'contains': operator.contains,

}

def process_conditionals(conditional_strings, variables):

for conditional_string in conditional_strings:

# Everything after first and op is part of second

first, op, second = conditional_string.split(None, 2)

resolved_operands = []

for raw_operand in (first, second):

try:

resolved_operand = ast.literal_eval(raw_operand)

except ValueError: # If the operand is not a valid literal

ve = sys.exc_info()

try:

# Check if the operand is a known value

resolved_operand = variables[raw_operand]

except KeyError: # If the operand is not a known value

# Re-raise the ValueError

raise ve[1], None, ve[2]

resolved_operands.append(resolved_operand)

yield (op, tuple(resolved_operands))

def main(lines, *conditional_strings):

for line in lines:

key, category, details = line

variables = {

'key': key,

'category': category,

'elapsed': details['elapsed'],

'jobname': details['jobname'],

}

conditionals = process_conditionals(conditional_strings, variables)

try:

# You could check each conditional separately to determine

# which ones have errors.

condition = all(OPERATORS[op](*operands)

for op, operands in conditionals)

except TypeError:

print("A literal in one of your conditionals is the wrong type. "

"If you can't see it, try running each one separately.",

file=sys.stderr)

break

except ValueError:

print("An operand in one of your conditionals is neither a known "

"variable nor a valid literal. If you can't see it, try "

"running each one separately.", file=sys.stderr)

break

else:

if condition:

print(line)

if __name__ == '__main__':

lines = [

[1, 'runtime', {'elapsed': 12.3, 'jobname': 'high38853'}],

[2, 'runtime', {'elapsed': 45.6, 'jobname': 'high38854'}],

[3, 'runtime', {'elapsed': 78.9, 'jobname': 'high38855'}],

[4, 'runtime', {'elapsed': 14.7, 'jobname': 'high38856'}],

[5, 'runtime', {'elapsed': 25.8, 'jobname': 'high38857'}],

[6, 'runtime', {'elapsed': 36.9, 'jobname': 'high38858'}],

[7, 'runtime', {'elapsed': 75.3, 'jobname': 'high38859'}],

]

conditional_strings = sys.argv[1:]

main(lines, *conditional_strings)

示例:

^{pr2}$

这是一个有趣的小项目:)。在

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值