my question is in regard to eval() 'ing a string that contains trusted-user input. I am not sure how to properly package the string (first line after try:). An exception is raised on eval() in the example below. 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!
str_complete_commandbefore you try to eval it?except, useexcept Exception, eand then includestr(e)in your print statement.