Answer the question
In order to leave comments, you need to log in
How to pass a command to a function containing exec()?
I'm making a function that will execute a command using exec and print the execution time. The variable ret is also provided, which, if an assignment is made using it, must be printed.
Experimental code :
def runner(code):
try :
t = time.time()
ret = ''
exec(code)
#print(ret)
t = time.time() - t
except:
print('error')
return "Error"
an = 'Time : '+ str(t)+'.Ans : '+str(ret)
return an
runner('ret = 10**5')
>>> code
'ret = 7'
>>> ret
''
>>> exec(code)
>>> ret
7
>>>
>>> runner('s = 19**2000000')
code = "s = 19**2000000"
try
'Time : 1.6354055404663086,Ans : '
>>> runner('s = 19**20000000')
code = "s = 19**20000000"
try
'Time : 59.313780546188354,Ans : '
>>>
Answer the question
In order to leave comments, you need to log in
Thanks for the help, found a solution for "scope in exec" :
...
try:
namespace = {'answer' : ''}
t = time.time()
exec(code, namespace)
t = time.time() - t
...
an = 'Time : '+ str(t)+'.Ans : '+str(namespace['answer'])
return an
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question