[英]Passing string properly to eval() in python
my question is in regard to eval() 'ing a string that contains trusted-user input. 我的问题是关于eval(),它是一个包含受信任用户输入的字符串。 I am not sure how to properly package the string (first line after try:).
我不确定如何正确打包字符串(try后的第一行:)。 An exception is raised on eval() in the example below.
在下面的示例中,eval()引发异常。 Any help would be highly appreciated.
任何帮助将不胜感激。 Here is an example code:
这是示例代码:
import ast
def do_set_operation_on_testids_file(str_filename1, str_filename2, str_set_operation):
resulting_set = None
with open(str_filename1) as fid1:
with open(str_filename2) as fid2:
list1 = fid1.readlines()
list2 = fid2.readlines()
try:
str_complete_command = "set(list1)." + str_set_operation + "(set(list2))"
resulting_set = ast.literal_eval(str_complete_command)
for each_line in resulting_set:
print(each_line.strip().strip('\n'))
except:
print('Invalid set operation provided: ' + str_set_operation)
Thanks very much! 非常感谢!
You don't need to use literal_eval()
or eval()
at all. 您根本不需要使用
literal_eval()
或eval()
。
Use getattr()
to get the set operation method by string: 使用
getattr()
通过字符串获取设置的操作方法:
>>> list1 = [1,2,3,2,4]
>>> list2 = [2,4,5,4]
>>> str_set_operation = "intersection"
>>> set1 = set(list1)
>>> set2 = set(list2)
>>> getattr(set1, str_set_operation)(set2)
set([2, 4])
Alternatively, you can pass an operator
function instead of a string with set method name. 另外,您可以传递一个
operator
而不是带有设置方法名称的字符串。 Example: 例:
>>> import operator
>>> def do_set_operation_on_sets(set1, set2, f):
... return f(set1, set2)
...
>>> do_set_operation_on_sets(set1, set2, operator.and_)
set([2, 4])
where and_
would call set1 & set2
, which is an intersection of sets. 其中
and_
将调用set1 & set2
,这是集合的交集。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.