NOTE: I'm assuming that what you mean by:
calling (entering and exiting) multiple times the same python code
is that you want to call the whole Python script multiple times, in which case you need to serialize your counter in some way external to the Python interpreter, to make it available next time. If you're just asking about calling the same function or method several times within one Python session, you can do that a variety of ways and I'd point you to mgilson's answer.
There are plenty of ways to serialize things, but your implementation doesn't really have anything to do with the language. Do you want to store it in a database? Write the value to a file? Or is it enough to just retrieve an appropriate value from context? For instance, this code will get you a new file each time it is called, based on the contents of output_dir. It's obviously rough, but you get the idea:
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 ''
Or of course you can just write a file called something like runnum.cfg somewhere next to the Python script, and write your current run number into it, then read that when the code launches.
pickleandshelfmodules both provide some interface for storing some constant values in files that persist between executions of a program. I'd look into those to start.saveworks like C'sstaticto clarify what you mean. There are more C users here than Fortran ones.