How To Reboot or Restart Python Script

Do you want to reboot or restart Python Script within itself? This article will show you how you can restart the Python script within itself.

If you are using an application or program that needs to be restarted after some update or after some user entry or maybe after a few minutes or seconds has been passed you can do this using the OS library in Python

Using execv From OS library

You can use execv method from the OS library to restart your python script or application. You can use the following command line parameters to relaunch your current application with the same command-line arguments as before:

os.execv(sys.argv[0], sys.argv)
os.execv(sys.executable, ['python3'] + sys.argv)
os.execv(sys.executable, ['python2'] + sys.argv)

Using system From OS Library

You can use the System method present in the OS library. This method lets you put the timer to restart the Python application or program you want. Below is the example code that you can use in your code.

#importing the OS library and Time Library
import os, time

#Unless the System Restart
while 1:
    print("Your Application is Restarting")
    time.sleep(0.2) # 200ms

The above code will restart the specific script of your application and once that has freed the memory you can quit the main application as well to restart your Python program.

Wrap Up

I hope you were able to get your Python application rebooted or restarted using the above methods provided. If you have any issues related to the above code let me know in the comment section.

Also, provide if you found any better method than the one discussed above I will be happy to add it here.

If you liked the above tutorial then please follow us on Facebook and Twitter. Let us know the questions and answer you want to cover in this blog.

Further Read:

  1. Python: To Check If String Contains a Substring
  2. Python: How To Check If a String Contains a List of Substring
  3. How To Return Null in Python Discussed
  4. How to Split a String into a List of Words or Letters in Python
  5. Reading A Binary File In Python With Examples

Leave a Comment