Restart Script in Python

In this tutorial, we will look into the method to restart or rerun the program in Python. Suppose we want to add the functionality to our program to restart when the user chooses the restart option; we need some method to rerun the program from within the program.
This tutorial will demonstrate the method that we can use to restart the program from within the program and kill the program’s current instance in Python. We can do so by using the following methods.
Как запустить код заново в Python?
Я захотел сделать простенькую игру на Python. Но вот проблема. Я не знаю какой командой запустить код заново. Я пошол в Гугл и там били такие вопросы. Но ответи на них мне не помогли. Мне нада какой-то PiP, либо функция чтобы запустить код заново. Методом создания функции давайте не будем))
Если нада вот код, согласен простенький, но я еще учусь))
import random
import time
random = ( random.randint(1, 2) )
number = float( input( ‘Введите число 1 либо 2. Если угадаете получите приз!’ ))
#угадал
if random == number:
a = str( input( ‘Вы угадали!! Дайте номер своего елект кошелька и ми начислим деньги. :’ ))
print( ‘Отлично!! Деньги прийдут через 5 минут.’ )
exit = input( ‘Програма завершена! Троян закроется через 15 секунд.\n Чтобы закрыть програму press f\n Спасибо что посмотрел до конца))) ‘ )
time.sleep(15)
elif exit == ‘f’:
SystemExit(1)
#не угадал
elif random != number:
b = input( ‘Вы не угадали(( Может попробуем снова ? (да, нет) :’ )
Restart python-script from within itself
I have a python-based GTK application that loads several modules. It is run from the (linux) terminal like so:
./myscript.py —some-flag setting
From within the program the user can download (using Git) newer versions. If such exists/are downloaded, a button appear that I wish would restart the program with newly compiled contents (including dependencies/imports). Preferably it would also restart it using the contents of sys.argv to keep all the flags as they were.
So what I fail to find/need is a nice restart procedure that kills the current instance of the program and starts a new using the same arguments.
Preferably the solution should work for Windows and Mac as well but it is not essential.
![]()
17 Answers 17
You’re looking for os.exec*() family of commands.
To restart your current program with exact the same command line arguments as it was originally run, you could use the following:
I think this is a more elaborate answer, as sometimes you may end up with too many open file objects and descriptors, that can cause memory issues or concurrent connections to a network device.
![]()
I know this solution isn’t technically what you are asking for but if you want to be 100% sure you freed everything or don’t want to rely on dependencies you could just run the script in from a loop in another:
Then you can restart main.py as simply as:
UPDATE — of the above answer with some example for future reference
And i have server.py where i need to restart the application itself, so i had:
but that did not restart the application itself by following runme.sh, so when i used this way:
Then i was able to restart itself
For me this part worked like a charm:
Works at Windows (Without args)
Try this work with Windows:
when you want to restart the script call this function
I have just a little amelioration on the code of #s3niOr.
In my case there are spaces in the path of the python file. So by adding a proper formatting, the problem can be solved.
Notice that in my case my python file has no other arguments. So if you do have other arguments, you have to deal with them.
This solves the problem of restarting a python script that has spaces in its path :
I was looking for a solution to this and found nothing that works on any of the stack overflow posts. Maybe some of the answers are too out of date, e.g. os.system has been replaced by subprocess. I am on linux lubuntu 17.10, using python 3.
Two methods worked for me. Both open a new shell window and run the main.py script in it and then close the old one.
1. Using main.py with an .sh script.
Adapted from @YumYumYum method. I did not need the kill option, (though it did not kill my python process by name anyway and I had to use killall python3 to achieve it when testing).
I use lxterminal but you could probably use any.
In the file called restart.sh (chmod +x to make it executable)
Then in the main.py use this when you need to call it
2. From within main.py
Adapted from @Stuffe method. This one is internal to the main.py script and opens a new shell window then runs the new script, then quits out of the old script. I am not sure it needs the time.sleep delay but I used it anyway.
![]()
Inspired by @YumYumYum and fixed the problem Using restart.sh and os.execl
Add this to your main.py
![]()
I’m using this to give an option for the users to restart the script within the console. Hope it could be a help.
So the user can input an option ‘Y/N’ to restart the program or not.
![]()
The old answers utilize exec which is fine, but not scalable in the long run. There’s also an approach of master/slave process relationship or a daemon/service in the background which will watch for the changes but is mostly OS specific or even different between the same family of OSs (init.d vs systemd vs whatever).
There’s also a middle ground by using a bootstraping technique and a simple subprocess.Popen() call thus assuming that the user who started the original program had the permissions to run the executable (such as /usr/bin/python ) should also work without any permission errors due to utilizing the exactly same executable. Bootstraping because it’s the main program that’s creating and calling the restarter a.k.a. pulling itself by own bootstraps after the initial start.
So a simple program (re)starter can be written like this, as written in the other answers:
Depending on your needs you might want to do some cleanup afterwards such as removing the (re)starter file.
This file would be called from your main program. However, your main program may have an exception, utilize sys.exit() , may be killed by a OS signal and so on. Python provides multiple hooks how to do something after such an event seamlessly, one of which is implemented by the atexit module. atexit doesn’t care about Python exceptions and about some signals either ( SIGINT ) (for further improvement check signal module), so it’s a reasonable choice before implementing own signal handler(s).
This allows you to register a function that will execute once your program stops. That function can be anything in Python, so it can write a file too.
How to Restart a Process in Python
You cannot restart a process in Python, instead you must create and start a new process with the same configuration.
In this tutorial you will discover how to simulate restarting a process in Python.
Let’s get started.
Table of Contents
Need to Restart a Process
A process is a running instance of a computer program.
Every Python program is executed in a Process, which is a new instance of the Python interpreter. This process has the name MainProcess and has one thread used to execute the program instructions called the MainThread. Both processes and threads are created and managed by the underlying operating system.
Sometimes we may need to create new child processes in our program in order to execute code concurrently.
Python provides the ability to create and manage new processes via the multiprocessing.Process class.
You can learn more about multiprocessing in the tutorial:
There may be cases where our new processes are terminated, either normally by finishing their execution or by raising an error, and we need to restart them.
This might be for many reasons such as:
- The process performs a useful action we wish to run periodically.
- The process is a daemon background task that we would like to always be running.
- The process is performing a task that can be restarted from a check-point.
Can a process be restarted in Python and if so how?
Run your loops using all CPUs, download my FREE book to learn how.
How to Restart a Process
Python process cannot be restarted or reused.
In fact, this is probably a limitation of the capabilities of processes provided by the underlying operating system.
Once a process has terminated you cannot call the start() method on it again to reuse it.
Recall that a process may terminate for many reasons such as raising an error or exception, or when it finishes executing its run() function.
Calling the start() function on a terminated process will result in an AssertionError indicating that the process can only be started once.
- AssertionError: cannot start a process twice
Instead, to restart a process in Python, you must create a new instance of the process with the same configuration and then call the start() function.
Now that we know we cannot restart a process but must instead re-create and start a new process, let’s look at some worked examples.
Confused by the multiprocessing module API?
Download my FREE PDF cheat sheet
Example of Restarting a Terminated Process
We can explore what happens when we attempt to start a terminated process in Python.
In this example we will create a new process to execute a target task function, wait for the new process to terminate, then attempt to restart it again. We expect it to fail with an AssertionError.
First, let’s define a target task function to execute in a new process.
The function will first block for a moment, then will report a message to let us know that the new process is executing.