Mattz Manz
Mattz Manz

Reputation: 43

How do I make Python code to execute only once?

I was thinking of how you execute code only once in Python. What I mean is setup code like when you set-up software; it only happens once and remembers you have already set up the software when you start the program again.

So in a sense I only want Python to execute a function once and not execute the function again even if the program is restarted.

Upvotes: 2

Views: 4122

Answers (3)

tangoal
tangoal

Reputation: 769

If you need a kind of Setup-Script to install a program or to setup your operating system's environment, then I would go even further. Imagine that your setup became inconsistent in the mean-time and the program does not work properly anymore. Then it would be good to provide the user a script to repair that.

If you execute the script the second time, then you can:

  • either check, if the setup was correct and print an error message to the user, if the setup became inconsistent in the mean-time
  • or check the setup and repair it automatically, if inconsistent

Just reading a text file or something similar (f.e. storing a key in the registry of windows) may bring you into the situation that the setup became inconsistent, but your setup-script will say that everything is fine, because the text file (or the registry key) has been found.

Furthermore, if doing so, this facilitates also to "uninstall" your program. Since you know exactly what has been changed for installation, you can revert it by an uninstall script.

Upvotes: 0

Dav2357
Dav2357

Reputation: 134

In addition to the method already proposed you may use pickle to save boolean variables representing whether some functions were executed (useful if you have multiple checks to carry out)

import pickle

f1_executed=True
f2_executed=False
pickle.dump([f1_executed,f2_executed],open("executed.pkl",mode='wb'))

##### Program Restarted #####

pickle.load(open("executed.pkl",mode='rb'))

Upvotes: 0

e11i0t23
e11i0t23

Reputation: 151

you could create a file once set up is complete for example an empty .txt file and then check if it exists when program runs and if not runs setup

to check weather a file exists you can use os.pathlike so

import os.path
if not os.path.exists(file_path):
   #run start up script
   file = open (same_name_as_file_path, "w") #creates our file to say startup is complete you could write to this if you wanted as well
   file.close

Upvotes: 2

Related Questions