How to Restart a Program in Python. In this tutorial, we will learn different methods to restart a Python program. Restarting a program can be useful in situations where the program needs to be refreshed due to updated configuration or to reset its states. We will cover various approaches, including using standard library functions and external library functions.
Table of Contents
Using the ‘os’ and ‘sys’ Modules
One of the simplest ways to restart a Python program is by utilizing 'os'
and 'sys'
modules. This method is straightforward and does not require any additional packages.
import os
import sys
def restart_program():
# Restarts the current program, with the file objects and descriptors cleanup
try:
# This command substitutes the current running proceess with a new process
os.execv(sys.executable,['python']+sys.argv)
except Exception as e:
print("Failed to restart program: ",e)
if __name__ == "__main__":
print("Program is running....")
# Calling the restart_program
restart_program()
This method uses 'os.execv()
‘, which replaces the current process with a new one. 'sys.executable'
provides the path to the Python interpreter currently running the script, and 'sys.argv'
contains the original command line argument.
Using the ‘subprocess’ Module
The 'subprocess'
module can also be used to restart a Python program. This approach spawns a new process and then exits the current process.
import subprocess
import sys
def restart_program():
# Restart the current program by starting a new sub process and exiting the old one
subprocess.Popen([sys.executable]+sys.argv)
sys.exit()
if __name__ == "__main__":
print("Program is running....")
# Calling the restart_program
restart_program()
In this example, 'subprocess.Popen()'
is used to start a new instance of the program before the existing program is terminated using 'sys.exit()'
.
Using External Libraries to Restart Python Program.
For more complex scenarios or to include additional features like delay before restart, you can use an external library like 'psutil'
handle the restart.
First, you will need to install the 'psutil'
library if you have not already.
pip install psutil
Then, you can implement the restart functionality as follows-
import os
import sys
import psutil
import time
def restart_program():
# Restarts the current program after ensuring no duplicate process are running
time.sleep(2)
# check for any other instance of this program and kill them
current_process = psutil.Process(os.getpid())
for proce in psutil.process_iter(['pid','name','cmdline']):
if proce.info['name'] == current_process.info['name'] and proce.info['pid'] != current_process.info['pid']:
if proce.info['cmdline'] == current_process.info['cmdline']:
proce.kill()
python = sys.executable
os.execl(python,python,* sys.argv)
if __name__ == "__main__":
print("Program is running....")
# Calling the restart_program
restart_program()
This code introduces a delay before the program restarts, which can be useful in situations where a cool-down period is needed between restarts.
Happy Coding & Learning
See Also
2 thoughts on “How to Restart a Program in Python”