用python保存变量值

2024-04-19 06:32:53 发布

您现在位置:Python中文网/ 问答频道 /正文


Tags: python
3条回答

注意:我假设您的意思是:

calling (entering and exiting) multiple times the same python code

您希望多次调用整个Python脚本,在这种情况下,您需要在Python解释器外部以某种方式序列化计数器,以便下次可以使用它。如果您只是想在一个Python会话中多次调用同一个函数或方法,那么可以通过多种方式来实现,我将向您指出mgilson's answer

有很多方法可以序列化,但是您的实现实际上与语言没有任何关系。是否要将其存储在数据库中?将值写入文件?或者仅仅从上下文中检索适当的值就足够了吗?例如,这段代码每次调用时都会根据output_dir的内容为您获取一个新文件。很明显很粗糙,但你知道:

import os

def get_next_filename(output_dir):
    '''Gets the next numeric filename in a sequence.

    All files in the output directory must have the same name format,
    e.g. "txt1.txt".
    '''

    n = 0
    for f in os.listdir(output_dir):
        n = max(n, int(get_num_part(os.path.splitext(f)[0])))
    return 'txt%s.txt' % (n + 1)

def get_num_part(s):
    '''Get the numeric part of a string of the form "abc123".

    Quick and dirty implementation without using regex.'''

    for i in xrange(len(s)):
        if s[i:].isdigit():
            return s[i:]
    return ''

当然,您也可以在Python脚本旁边的某个地方编写一个名为runnum.cfg的文件,并在其中写入当前的运行号,然后在代码启动时读取它。

mgilson's response为原始问题提供了很好的选项。另一种方法是重构代码,将选择文件名与计算+保存分离开来。下面是代码草图:

for i in ...:
   filename = 'txt%d.txt' % (i,)
   do_something_then_save_results(..., filename)

如果您需要在很多地方执行此操作并希望减少代码重复,则生成器函数可能非常有用:

def generate_filenames(pattern, num):
   for i in xrange(num):
       yield pattern % (i,)

...
for filename in generate_filenames('txt%d.txt', ...):
   do_something_then_save_results(..., filename)

将“…”替换为应用程序中有意义的内容。

不是真的。最好使用全局变量:

counter = 0
def count():
    global counter
    counter += 1
    print counter

另一种不需要全局声明的方法是:

from itertools import count
counter = count()
def my_function():
    print next(counter) 

甚至:

from itertools import count
def my_function(_counter=count()):
    print next(_counter)

最终版本利用了函数是一类对象这一事实,并且可以随时向函数添加属性:

def my_function():
    my_function.counter += 1
    print my_function.counter

my_function.counter = 0 #initialize.  I suppose you could think of this as your `data counter /0/ statement.

但是,看起来您实际上想要将计数保存在文件或其他内容中。这也不难。您只需选择一个文件名:

def count():
    try:
        with open('count_data') as fin:
            i = int(count_data.read())
    except IOError:
        i = 0
    i += 1
    print i
    with open('count_data','w') as fout:
        fout.write(str(i))

相关问题 更多 >