Z
Z
zavilskij_nikita2016-06-05 19:15:57
Python
zavilskij_nikita, 2016-06-05 19:15:57

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

Call example: But the output of the changed ret does not occur, although if you try to do it in the shell, everything works:
runner('ret = 10**5')
>>> code
'ret = 7'
>>> ret
''
>>> exec(code)
>>> ret
7
>>>

In the function itself, execution is clearly taking place - with the complication of the task, the timer shows an increased value:
>>> 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 : '
>>>

Where is the mistake?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
#
#algooptimize #bottize, 2016-06-05
@zavilskij_nikita

scope in exec google it.

Z
zavilskij_nikita, 2016-06-06
@zavilskij_nikita

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 question

Ask a Question

731 491 924 answers to any question