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

Edited 2 Years Ago by Gribouillis

Comments
Nice!
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()

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

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.

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.

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 ?

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

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.

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.

Comments
No harm done.

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

Any help greatly appreciated

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.

Edited 1 Year Ago by Gribouillis

Comments
Thanks for that, I'm now using a while loop instead.

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.

Edited 1 Year Ago by Gribouillis

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

@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.

@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

Edited 2 Weeks Ago by Aman_7

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 ?

The article starter has earned a lot of community kudos, and such articles offer a bounty for quality replies.