0

I want to be able to restart my Python script, or just basically remove every variable and its value from its memory and start the program from line 1 (or line 0 if you count like a computer).

I need the script to fully restart a server every midnight - in that being resting all variables and starting back up. My original file is about 400-450 lines, and the example is just to show what I want to achieve.

Example code if you still don't understand:

print("test")
a = 5
b = "xyz"
c = [5, 3, 72, 56]
d = dir("C:\\Users\\User")
x = 6
y = "xyz"
z = [5, 2]

del x
del y
del z

def restart():
    #Code to restart here
    #I have tried the following code before:
    del a, b, c, d, x, y, z
    #This will not work, it just causes an:
    #"UnboundLocalError: local variable 'a' referenced before assignment"
    #Putting all the variables into the required positional argument will 
    #cause an error with non existing variables, like x, y and z in this example.
    #Is there any other way of restarting or deleting all currently existing variables?


restart()
Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
  • put them in a scope of some sort, for example put all of your code in a function – sam46 Jan 31 '19 at 17:01
  • Could you provide some *context* - why do you want to do this? – jonrsharpe Jan 31 '19 at 17:01
  • jonrsharpe I need the script to fully restart a server every midnight - in that being resting all variables and starting back up. My original file is about 400-450 lines, and the example is just to show what I want to achieve. – Marcel Barlik Feb 01 '19 at 22:38

1 Answers1

0

You could encapsulate your code in a loop, or function, and execute it over and over.

Something like:

import time

while 1:
  print("test")
  a = 5
  b = "xyz"
  c = [5, 3, 72, 56]
  d = dir("C:\\Users\\User")
  x = 6
  y = "xyz"
  z = [5, 2]
  time.sleep(5)
  # Sleeps for 5 seconds
  # This prevents the code from running too many times per second and crashing your pc
Mikael Brenner
  • 357
  • 1
  • 7
  • That will run the code without deleting all the variables and their values. And putting a time.sleep(x) inside of my def, will not restart my server and create new variables and files. – Marcel Barlik Feb 01 '19 at 22:41