views:

555

answers:

4

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 = 5000
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______()
A: 

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.

Lennart Regebro
A: 

The following statement declares i as global variable:

global i
Denis Otkidach
A: 

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.

Robert Rossney
A: 

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']
Paul Du Bois