I want to create a variable called this_is_the_first_run which will be stored in the ‘main.py’ file and it should indicate whether this is the first time the project is run. Basically, code I’m trying to write look like this:
If this_is_the_first_run == 1:
os.system('python first_run.py')
But I don’t know where to assign and store this variable as I can’t put it in my ‘first_run.py’. Neither can I assign value to this variable somewhere in the main file.
What is the best approach to that?
>Solution :
Variables generated during code execution do not, by themselves, have an existence that endures beyond the execution of your code. If you want the values of variables to persist beyond code execution, you need to write the values you wish to endure to a file on disc, and then access/read/write those files as part of your code execution.
An example of how you can achieve what you’re describing is given below:
# This is the main function. Each time it's run, the variable "run_count" is
# retrieved by reading run_count.txt, and its value is incremented by 1, and
# written back to run_count.txt.
def main():
# check if "run_count.txt" exists. If it does, read its current count and
# assign it to the variable run_count.
try:
with open('run_count.txt', 'r') as f:
run_count = int(f.read())
# If run_count.txt does not yet exist, create it and write the value 0 to it.
except FileNotFoundError:
with open('run_count.txt', 'w') as f:
run_count = 0
f.write(str(run_count))
# Insert actual main() code here:
print ("Now the script does whatever you want.")
# Now that your main() function has been run, increment the value of run_count
# by 1 and write the new value to run_count.txt.
run_count += 1
with open('run_count.txt', 'w') as f:
f.write(str(run_count))
# print the current run_count to screen
print(f'This script has been run {run_count} {"times." if run_count > 1 else "time."}')
main()
# Now the script does whatever you want.
# This script has been run 1 time.
main()
# Now the script does whatever you want.
# This script has been run 2 times.
main()
# Now the script does whatever you want.
# This script has been run 3 times.
main()
# Now the script does whatever you want.
# This script has been run 4 times.
main()
# Now the script does whatever you want.
# This script has been run 5 times.
In this case, a single value is written to a txt file. If you wanted multiple values, or more complex data structures to endure, there is a host of options available – from using larger/longer txt files, csvs, jsons, or databases.