I have a Python script that I want to increment a global variable every time it is run. Is this possible?
-
5You'd most likely need to store the variable value in some form of external storage to the script and then reassign it each time. Such as to a file. – Aklys May 16 '17 at 22:41
-
You need to grok the difference between source code and your program as it is run in memory. If you want the data to continue after the process terminates, you need to save the data to long-term storage, and reload it each time you run the process. https://en.wikipedia.org/wiki/Persistence_(computer_science) – juanpa.arrivillaga May 16 '17 at 22:42
4 Answers
Pretty easy to do with an external file, you can create a function to do that for you so you can use multiple files for multiple vars if needed, although in that case you might want to look into some sort of serialization and store everything in the same file. Here's a simple way to do it:
def get_var_value(filename="varstore.dat"):
with open(filename, "a+") as f:
f.seek(0)
val = int(f.read() or 0) + 1
f.seek(0)
f.truncate()
f.write(str(val))
return val
your_counter = get_var_value()
print("This script has been run {} times.".format(your_counter))
# This script has been run 1 times
# This script has been run 2 times
# etc.
It will store in varstore.dat
by default, but you can use get_var_value("different_store.dat")
for a different counter file.
-
This is a very reasonable solution for a simple counter of how many times a script has been run. Although, I believe you want to open in `'r+'` mode, or else the file cursor will be at the end and you'd have to seek at the beginning... but I always get that confused... EDIT: [nevermind](http://stackoverflow.com/a/13248062/5014455) – juanpa.arrivillaga May 16 '17 at 23:12
-
Nope, `a+` with `.read()` gets you the whole file, `r+` would fail if the file doesn't exist. This method doesn't even require to have the file created upfront. – zwer May 16 '17 at 23:15
example:-
import os
if not os.path.exists('log.txt'):
with open('log.txt','w') as f:
f.write('0')
with open('log.txt','r') as f:
st = int(f.read())
st+=1
with open('log.txt','w') as f:
f.write(str(st))
Each time you run your script,the value inside log.txt will increment by one.You can make use of it if you need to.

- 65
- 3
Yes, you need to store the value into a file and load it back when the program runs again. This is called program state serialization or persistency.

- 7,685
- 3
- 31
- 36
-
Can you give a quick example of how this is done? Or what packages I should look at? Thanks. – Char May 16 '17 at 22:54
-
1@Char have you tried googling "how to write to a file in Python"? – juanpa.arrivillaga May 16 '17 at 22:55
-
I know how to write and read from files. But is there no way to increment without reading from a file? – Char May 16 '17 at 22:57
-
@Char what? You can *increment* some variable without involving a file at all, the issue is *persisting that state*. You can't change a file without opening it and reading/writing to it. – juanpa.arrivillaga May 16 '17 at 22:59
-
No, you can't because of how computers and operating systems are built. The main reason is that primary memory is volatile. Secondary memory, like a hard disk, is permanent. The operating system also throws away all allocated data from primary memory when a program exits. – hdante May 17 '17 at 05:11
For a code example:
with open("store.txt",'r') as f: #open a file in the same folder
a = f.readlines() #read from file to variable a
#use the data read
b = int(a[0]) #get integer at first position
b = b+1 #increment
with open("store.txt",'w') as f: #open same file
f.write(str(b)) #writing a assuming it has been changed
The a variable will I think be a list when using readlines.

- 753
- 9
- 20
-
"#a buffer for the file content" doesn't do what you say, and is totally unecessary, and `f.write(a)` will throw an `TypeError` because `a` will be a list, and `.write` expects a `str`. – juanpa.arrivillaga May 16 '17 at 23:03
-
actually it works in python 2.7 but I didn't specify use case as variable increment. fixed now – pointerless May 16 '17 at 23:05
-
As it was written, no it would not work in Python 2.7, but your edit: `f.write(str(a))` does fix the *error*. However, you would be writing a *string* representation of a list, which you would then have to parse on the way back. Furthermore, `a = []` is **still** unnecessary. Also, what you've show to increment the integer won't actually modify the list. – juanpa.arrivillaga May 16 '17 at 23:06
-
@juanpa.arrivillaga you misread, but I've removed the a declaration. That works. – pointerless May 16 '17 at 23:10
-
There never *was* a declaration. Python doesn't have variable declarations... which was the point I was trying to make. But yes, I misread that you were now writing `str(b)`. – juanpa.arrivillaga May 16 '17 at 23:11