重新启动脚本或删除所有已知变量

时间:2019-01-31 16:59:07

标签: python python-3.x windows restart

我希望能够重新启动Python脚本,或者基本上从内存中删除每个变量及其值,然后从第1行(如果您像计算机一样计数,则从第0行)启动程序。

我需要脚本在每个午夜完全重新启动服务器-休息所有变量并重新启动。我的原始文件大约有400-450行,该示例只是为了展示我想要实现的目标。

如果您仍然不了解,请参见示例代码:

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()

1 个答案:

答案 0 :(得分:0)

您可以将代码封装在循环或函数中,然后一遍又一遍地执行。

类似的东西:

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