蟒蛇 |脚本执行后如何使局部变量全局

发布于 2024-08-08 12:03:35 字数 690 浏览 11 评论 0原文

这是代码。我需要做的是找到一种方法使i成为全局的,这样在重复执行时i的值就会增加1,而不是每次都重置为0。 main 中的代码来自我嵌入到“main”中的另一个脚本,以便使跟踪功能正常工作。这一切都是由 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______()

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______()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

反话 2024-08-15 12:03:35

不幸的是,您对问题的编辑如此之多,以至于人们对它的回答显得毫无意义。

有多种方法可以创建作用域在函数内的变量,该变量的值在调用之间保持不变。它们都利用了函数是一等对象这一事实,这意味着它们可以具有属性。例如:

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

还有一种技巧是使用列表作为参数的默认值,然后在调用函数时从不为参数提供值:

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

......但我不建议使用它,除非你明白为什么它有效,但也许那时也无效。

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.

居里长安 2024-08-15 12:03:35

您需要做两件事才能使变量成为全局变量。

  1. 在全局范围内定义变量,即在
    功能。
  2. 在函数中使用全局语句使得Python
    知道这个函数应该使用更大的作用域变量。

例子:

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

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
如痴如狂 2024-08-15 12:03:35

未在函数或方法中定义但在 Python 中模块级别定义的变量与 Python 中的全局变量一样接近。您可以通过另一个脚本访问它,

from scriptA import variablename

这将执行该脚本,并允许您访问该变量。

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.

又怨 2024-08-15 12:03:35

以下语句将 i 声明为全局变量:

global i

The following statement declares i as global variable:

global i
疧_╮線 2024-08-15 12:03:35

您的声明“嵌入'main'以使跟踪功能正常工作”是相当含糊的,但听起来您想要的是:

  • 从用户那里获取输入,
  • 在某个持久上下文中执行它,
  • 如果花费太长时间,则中止

执行这种事情,使用“exec”。一个例子:

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']

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']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文