注意:我假设您的意思是: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的文件,并在其中写入当前的运行号,然后在代码启动时读取它。