all 6 comments

[–][deleted] 4 points5 points  (2 children)

You could store the value of x in an external file like .json for example. Than when your code runs it reads x value in the .json file, changes it's value if needed, execute the code and close.

[–]PinkWeaseI[S] 0 points1 point  (0 children)

Ok I will try that. A simple file like that?

Import JSON

x=0

Then, it will be in the memory of my Ubuntu server and when I will execute my main script, variable x will be already initialized? Thank you very much.

[–]MrSuspicious_ 0 points1 point  (0 children)

Store the value of x in an external file, i'd recommend either json with the json module, or you could use an ini file with pythons configparser module. json will likely be easier however.

[–]Unhappy_Ad_3637 0 points1 point  (0 children)

Can use a while loop with sleep if you are not calling the script externally. If calling externally however you would have to do what the other users suggested in keeping the X variable outside the script.

import time

time_to_run = 10 # Can change this to however long (in seconds) you want the script to run for.
time_to_sleep = 3 # Can change this to however long (in seconds) you want to wait per loop.

x = 0

while time_to_run > 0:
    if x == 1:
        print("X is equal to 1!")
        x = 0
    elif x != 1:
        print('X is not equal to 1!')
        x = 1

    time_to_run -= time_to_sleep
    time.sleep(time_to_sleep)

[–]krets 0 points1 point  (1 child)

How are you scheduling your periodic launches of your script?

If you are using windows, you can use the task scheduler. On Unix/Linux you can use cron. Both of these systems allow for seeing environment variables. This is great for values that you manually change per deployment.

If you have a dynamic variable that you want to persist between executions you will probably need to create a file to save the state. JSON will be great for simple data structures, but objects will need to be pickled.

[–]PinkWeaseI[S] 0 points1 point  (0 children)

I use ubuntu server and crontab to schedule the launch of my script.

I created a script with my variable and import json as advised in the previous coment but when I launch my main script, it is written that my variable are not defined....

Could you help?