开发者

Python | How to make local variable global, after script execution

Here is the code. What I need to do is find a way to make i global so that upon repeated executions the value of i will increment by 1 instead of being reset to 0 everytime. The code in main is from another script that I embed in 'main' in order to have the trace function work. This is all being done from Java.

from __future__ import nested_scopes
import sys
import time

startTime = time.time()
timeLimit = 50开发者_如何学JAVA00
def traceit(frame, event, arg):
if event == "line": 
    elapsedTime = ((time.time() - startTime)*1000)
    if elapsedTime > timeLimit:
         raise Exception, "The execution time has exceeded the time limit of " + str(timeLimit) + " milliseconds. Script will now terminate"
return traceit

sys.settrace(traceit)
def main______():
    try:
        i+=1
    except NameError:
        i=1
main______()


It's unfortunate that you've edited the question so heavily that peoples' answers to it appear nonsensical.

There are numerous ways to create a variable scoped within a function whose value remains unchanged from call to call. All of them take advantage of the fact that functions are first-class objects, which means that they can have attributes. For instance:

def f(x):
    if not hasattr(f, "i"):
       setattr(f, "i", 0)
    f.i += x
    return f.i

There's also the hack of using a list as a default value for an argument, and then never providing a value for the argument when you call the function:

def f(x, my_list=[0]):
   my_list[0] = my_list[0] + x
   return my_list[0]

...but I wouldn't recommend using that unless you understand why it works, and maybe not even then.


You need to do two things to make your variable global.

  1. Define the variable at the global scope, that is outside the function.
  2. Use the global statement in the function so that Python knows that this function should use the larger scoped variable.

Example:

i = 0
def inc_i():
  global i
  i += 1


A variable not defined in a function or method, but on the module level in Python is as close as you get to a global variable in Python. You access that from another script by

from scriptA import variablename

That will execute the script, and give you access to the variable.


The following statement declares i as global variable:

global i


Your statement "embed in 'main' in order to have the trace function work" is quite ambiguous, but it sounds like what you want is to:

  • take input from a user
  • execute it in some persistent context
  • abort execution if it takes too long

For this sort of thing, use "exec". An example:

import sys
import time

def timeout(frame,event,arg):
    if event == 'line':
        elapsed = (time.time()-start) * 1000

code = """
try:
    i += 1
except NameError:
    i = 1
print 'current i:',i
"""
globals = {}

for ii in range(3):
    start = time.time()
    sys.settrace(timeout)
    exec code in globals
    print 'final i:',globals['i']
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜