0

I am developing a mix of scripts in different languages that creates datamatrix. Mi program can create thousands of datamatrix in seconds but the structure of my datamatrix is not correct.

Mi program generates IDs and it follows an structure.

One part of the ID is a counter.

My question is... How can I save the value of my content? When I finish to create datamatrix the program closes and the counter evidently restarts.

I know how to do this, it is easy, but I do not like at all. I can save the value in another file and take it each time I begin the program, but it will create a new file and I do not want it. That program is not for me, and

If I have no more and better options I will create the new file which will set and get the counter.

Adrián
  • 1
  • 4
  • variants of your suggestion are basically the only option. files are used to store the state when your program isn't executing. there are lots of ways of packaging this up (simple/custom text files, standardised file formats like JSON, SQL/relational databases, in the cloud) but they all amount to the same thing, a place to store state "outside" the program – Sam Mason May 16 '19 at 11:49
  • Finally I decided to write it in a file and try to protect the file the best possible. Thank you – Adrián May 17 '19 at 06:29

1 Answers1

0

You can save the counter by using environment variables.
First, set an environment variable for the counter. This can be done (in the question linked) by using:

import os
os.environ['COUNTER'] = '0'

However, if the environment variable doesn't exist, then getting the environment variable will return a KeyError.
Therefore, we would need to add an try-except statement to check if the environment variable exists:

import os
try:
    counter = int(os.environ['COUNTER'])
except KeyError:
    counter = 0

At the end of a program, we would need to save the counter variable to the environment variable.
To do this, we simply do:

os.environ['COUNTER'] = str(counter)

Therefore, for a final program, we get:

TL;DR ([It was] too long; [I] didn't read)

import os
try:
    counter = int(os.environ['COUNTER']
except KeyError:
    counter = 0
# Do anything with the counter 
os.environ('COUNTER') = str(counter)

However, you should be wary that environment variables have to be strings.

MilkyWay90
  • 2,023
  • 1
  • 9
  • 21
  • I did not know that we could do that. But finally is "the same" like saving the data in another file. Thank you – Adrián May 17 '19 at 06:27
  • @Adrián `the same` returns a `SyntaxError`; therefore, it does not utilize I/O to other files. Therefore, the answer to your question is no. – MilkyWay90 May 17 '19 at 23:47