I have the following code which manipulates a function in the form of string and adds a timer to while loops to see if they take 2 seconds without returning. If so it returns 'error, infinite loop.'
Right now when I run this code it gives me a "TypeError: 'str' object is not callable".
def nico():
otherTimer = '\n current_time = time.time()\n elapsed_time = current_time - start_time\n print(elapsed_time)\n if elapsed_time > 2:\n return "error, infinite loop"'
sample = '''def sample():\n a = 1\n while a == 1:\n print("breh")
'''
for k in range(len(sample)): # insert srart time at top of function
if sample[k] == ":":
sample = sample[:k + 1] + "\n start_time = time.time()\n" + sample[k+1:]
break
if "while" in sample: #insert timer in the while loop
for i in range(len(sample)):
if sample[i] + sample[i + 1] + sample[i + 2] + sample[i + 3] + sample[i + 4] == 'while':
newstring = sample[i:]
for j in range(len(newstring)):
if newstring[j] == ':':
print(sample[:i] + sample[i:] + otherTimer)
output = sample[:i] + sample[i:] + otherTimer
exec(output)
return eval('sample()')
I'm confused because this piece of code does what I want it to do, and the only difference is that I am storing the string function as the actual string instead of a variable in my exec() statement:
def delly():
exec('def sample():\n start_time = time.time()\n\n a = 1\n while a == 1:\n print("breh")\n \n current_time = time.time()\n elapsed_time = current_time - start_time\n print(elapsed_time)\n if elapsed_time > 2:\n return "error, infinite loop"')
return eval('sample()')