Restart your python program.

Updated Gribouillis 5 Tallied Votes 74K Views Share

This snippet defines a function restart_program() which restarts your python program from within your python program.

Pupo commented: Nice! +5
import sys
import os

def restart_program():
    """Restarts the current program.
    Note: this function does not return. Any cleanup action (like
    saving data) must be done before calling this function."""
    python = sys.executable
    os.execl(python, python, * sys.argv)

if __name__ == "__main__":
    answer = raw_input("Do you want to restart this program ? ")
    if answer.lower().strip() in "y yes".split():
        restart_program()
Stefano Mtangoo 455 Senior Poster

Cool thanks!
Simple and elegant

Boubakr 0 Newbie Poster

Great...

Edwin Okli 6 Newbie Poster

This code is not working on my version of Python (3.2). It just restarts the shell and does not do anything else.

Gribouillis 1,391 Programming Explorer Team Colleague

This code is not working on my version of Python (3.2). It just restarts the shell and does not do anything else.

If you are using this in Idle, it won't work because the python process running in the shell is different from Idle gui's process. This will only restart the process running in the shell, not Idle itself.

Edwin Okli 6 Newbie Poster

If you are using this in Idle, it won't work because the python process running in the shell is different from Idle gui's process. This will only restart the process running in the shell, not Idle itself.

It is not working in either the shell or Idle. It's strange because when I was running the program on another computer (which I suppose must use a different version of Python) it worked completely fine.

Gribouillis 1,391 Programming Explorer Team Colleague

It is not working in either the shell or Idle. It's strange because when I was running the program on another computer (which I suppose must use a different version of Python) it worked completely fine.

What do you exactly mean by 'the shell' ? also what's your OS ?

Edwin Okli 6 Newbie Poster

What do you exactly mean by 'the shell' ? also what's your OS ?

i.e. I double-click the .py file to execute it. It works in both the shell and IDLE in the version which I use at home (Python 3.1.2 on Windows Vista) but neither in the version I use at school (Python 3.2 on Windows 7).

TrustyTony 888 pyMod Team Colleague Featured Poster

Is that 3.2 3.2.2 as there was an issue with input statement with 3.2.1? Probably not reason though, at that problem would make program OK in IDLE and not OK in direct excecution.

Edwin Okli 6 Newbie Poster

Sorry about this, it turns out it was just my account... which is a bit bizarre but it seems to be working fine for others.

Lucaci Andrew commented: No harm done. +6
Aoradon 0 Newbie Poster

Wow thanks so much!

Louis_2 14 Newbie Poster

This just restarts the shell
How do i get it to run the program again?

Any help greatly appreciated

Gribouillis 1,391 Programming Explorer Team Colleague

This just restarts the shell

are you using idle ? another ide ?

Louis_2 14 Newbie Poster

I'm using IDLE

Gribouillis 1,391 Programming Explorer Team Colleague

I'm using IDLE

Idle has 2 processes, the first one (say process A) to run the IDLE GUI, the second one (say process B) to run your python code. Restarting the shell in idle means to kill process B to start a new one.

This snippet only restarts the process where it is called, in our case, it restarts process B, but it won't restart Idle. As far as I know, there is no way to restart process A from your program because your python program has no notion that it is running in Idle.

The Idle process could be restarted programmatically by exploring the processes running on your computer and calling appropriate commands, but I don't think it would be very useful. Why do you want to restart Idle ?

Edit: actually, in idle it won't work well because the idle process A starts your process B with pipes to communicate with B, so that you can read data printed by your program in the idle console or send data to your program by writing in the idle console. Unfortunately, the pipes wont be enabled after restart_program(), which means that your program restarts but can't communicate with the idle console. I'll try to design a small test program to show this.

Louis_2 commented: Thanks for that, I'm now using a while loop instead. +0
Gribouillis 1,391 Programming Explorer Team Colleague

Here is a small tkinter example which shows this

import Tkinter as tk
# adapted from http://www.python-course.eu/python_tkinter.php

counter = 0 
def counter_label(label):
  def count():
    global counter
    counter += 1
    label.config(text=str(counter))
    label.after(1000, count)
  count()

def restart(*args, **kwargs):
  from kernilis.utils import restart_program
  restart_program()

print("Hello from tkinter counter example!")
root = tk.Tk()
root.title("Counting Seconds")
label = tk.Label(root, fg="green")
label.pack()
counter_label(label)
button = tk.Button(root, text='Stop', width=25, command=root.destroy)
button.pack()
button = tk.Button(root, text='Restart Program', width=25, command=restart)
button.pack()
root.mainloop()

(you may need to adapt the name of the module containing restart_program()). This program prints a banner message, then runs a small tkinter window. When this program is run into idle and restarted, the tkinter window reappears, which proves that the program restarts, but the banner message is only printed the first time, which proves that the pipes communicating with idle don't work for the subsequent program instances.

When this program is run in a console, such as a linux console or a cmd console in windows, the banner message is printed every time the program is restarted.

Aman_7 0 Newbie Poster

Hii...I am using Python idle 3.4.2,i want to restart my whole python program from the declaration of all libraries....whenever i try your method of "restart program"...it justs restart the shell and the controller doesnt enter into the first function and my GUI is also persistent.
Can you please help me to solve this problem i really need this thing to be solved...i have written my program more than 5000 lines...so now i dont want to make big changes in that...or please suggest me an alternate to solve that
i am using raspberry pi 3 and my OS is Raspbian

Gribouillis 1,391 Programming Explorer Team Colleague

@aman_7 your question is a little too vague. Did you try to run your code outside of idle (from an ordinary terminal) to see what it does ?

You could perhaps start your own thread an describe with more details what your program does and what you want to do and why it doesn't work.

Aman_7 0 Newbie Poster

@Gribouillis ,thanks for replying.
Ok, so i just give you an example code of what i want to do
Code:

  import sys
  import os
 def restart():
     python = sys.executable
     os.execl(python,python, * sys.argv)
 print("h")
 restart()

i want to print "h" again and again every time i call a restart function....but it prints it once and restarts the shell and then wont print it again....using program restart...for my program i cant use while loop or any kind of return function
so please help me out to solve this problem
Thanks

Gribouillis 1,391 Programming Explorer Team Colleague

There are two ways to restart your program: either you exit the running process and you start a new one, this is what this snippet does, or you stay in the same process, free all objects, flush buffers, and restart the main program's action by the means of a loop. This snippet uses the first solution. It is a radical way to restart, and it guarantees a fresh start. Only it won't work completely in python's idle IDE because the input and output pipes are not inherited by the new process, which means for example that the program restarts but you don't see any output in Idle's console. If you run your program from a bash terminal, you'll see that it works.

Why don't you want to use a loop ?

Claire_2 0 Newbie Poster

Thanks. Really simple. Just wordering, how exactly does it work. Does it make the script and executable or something?

Gribouillis 1,391 Programming Explorer Team Colleague

@Claire_2 It works by calling the execl system function. This is a fundamental mechanism of the OS that also belongs to the posix standard (See here).

Aman_7 0 Newbie Poster

@Gribouillis......Sorry for the late reply..........I cant use a loop because I am using python's tkinter library which doesnt work in a loop and snipet is not working for me as i am using idle...still cant find a solution to my problem

Gribouillis 1,391 Programming Explorer Team Colleague

@Aman_7 The only thing that doesn't work in your case is input/output to the console. Your tkinter program could create a text widget and redirect its output to the text widget. There is an example <here>.

S._1 0 Newbie Poster

Thanks for posting your Code!
I'm sorry, for asking too but I'm stuck with the same problem. I'm new to Python and I was also wondering why the shell says "Restart" but my program won't come back... How do I have to execute my script do make the restart working? When I try to start it via CMD in Windows it won't show the GUI I've made with tkinter ...

Thanks in advance for your help!

Gribouillis 1,391 Programming Explorer Team Colleague

@S._1 Can you start you own thread and post your code ? We could probably diagnose why your GUI doesn't show.

S._1 0 Newbie Poster

Thanks for replying so quickly. I've now found out that it was because of the mainloop() not being at the right position at the end of my script (anyway it would probably be to much code to post ... ^^). Well, now it works.
But still, when I start the program via CMD and trigger the piece of code to restart the script, the window shuts down and does not come back again ... :/

Gribouillis 1,391 Programming Explorer Team Colleague

But still, when I start the program via CMD and trigger the piece of code to restart the script, the window shuts down and does not come back again

Without, the code, it is impossible to debug. You could perhaps write a minimal example where this snippet fails and start a new thread with the issue. There is most certainly a solution, because this snippet invokes a very low level feature of the operating system, and I don't see how it could fail.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.