Автоматический перезапуск программы python

Restart your python program.

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

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.

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.

Читайте также:  Function inside function javascript this

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.

import Tkinter as tk # adapted from ' data-bs-template=' '>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.

Читайте также:  Java thread stop is deprecated

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

Источник

Как создать «перезапуск кода» на Python?

Всем доброго, изучаю питон самостоятельно, написал программу которая переводит числа в квадрат, в конце если пользователь пишет «Да» что бы либо он перезагружал либо зациклил этот код.
Чтобы не искать, все в низу.

#Переводчик квадратов чисел
#Приветствие
print(«Добро пожаловать в \»Переводчик квадратов чисел\»»)
start=input(«Начинаем работать?(Да,Нет): » )

#консоль начала работы
if start==»Да»:
number=int(input(«Введите число,которое нужно перевести: » ))#ввод числа
elif start==»Нет»:
print(«Досвидания =(«)
exit()
else:
restart=bool(print(«Напишите Да/Нет(С заглавной буквы)»))
if restart==False:
exit()

#список квадратов
if number==0:
print(«Результат:0»)
elif number==1:
print(«Результат:1»)
elif number==2:
print(«Результат:4»)
elif number==3:
print(«Результат:9»)
elif number==4:
print(«Результат:16»)
elif number==5:
print(«Результат:25»)
elif number==6:
print(«Результат:36»)
elif number==7:
print(«Результат:49»)
elif number==8:
print(«Результат:64»)
elif number==9:
print(«Результат:81»)
elif number==10:
print(«Результат:100»)
elif number==11:
print(«Результат:121»)
elif number==12:
print(«Результат:144»)
elif number==13:
print(«Результат:169»)
elif number==14:
print(«Результат:196»)
elif number==15:
print(«Результат:225»)
elif number==16:
print(«Результат:256»)
elif number==17:
print(«Результат:289»)
elif number==18:
print(«Результат:324»)
elif number==19:
print(«Результат:361»)
elif number==20:
print(«Результат:400»)
elif number==21:
print(«Результат:441»)
elif number==22:
print(«Результат:484»)
elif number==23:
print(«Результат:529»)
elif number==24:
print(«Результат:576»)
elif number==25:
print(«Результат:625»)
elif number==26:
print(«Результат:676»)
elif number==27:
print(«Результат:729»)
elif number==28:
print(«Результат:784»)
elif number==29:
print(«Результат:841»)
elif number==30:
print(«Результат:900»)
elif number==31:
print(«Результат:961»)
elif number==32:
print(«Результат:1024»)
elif number==33:
print(«Результат:1089»)
elif number==34:
print(«Результат:1156»)
elif number==35:
print(«Результат:1225»)
elif number==36:
print(«Результат:1296»)
elif number==37:
print(«Результат:1369»)
elif number==38:
print(«Результат:1444»)
elif number==39:
print(«Результат:1521»)
elif number==40:
print(«Результат:1600»)
elif number==41:
print(«Результат:1681»)
elif number==42:
print(«Результат:1764»)
elif number==43:
print(«Результат:1849»)
elif number==44:
print(«Результат:1936»)
elif number==45:
print(«Результат:2025»)
elif number==46:
print(«Результат:2116»)
elif number==47:
print(«Результат:2209»)
elif number==48:
print(«Результат:2304»)
elif number==49:
print(«Результат:2401»)
elif number==50:
print(«Результат:2500»)
elif number==51:
print(«Результат:2601»)
elif number==52:
print(«Результат:2704»)
elif number==53:
print(«Результат:2809»)
elif number==54:
print(«Результат:2916»)
elif number==55:
print(«Результат:3025»)
elif number==56:
print(«Результат:3136»)
elif number==57:
print(«Результат:3249»)
elif number==58:
print(«Результат:3364»)
elif number==59:
print(«Результат:3481»)
elif number==60:
print(«Результат:36»)
elif number==61:
print(«Результат:36»)
elif number==62:
print(«Результат:36»)
elif number==63:
print(«Результат:36»)
elif number==64:
print(«Результат:36»)
elif number==65:
print(«Результат:36»)
elif number==66:
print(«Результат:36»)
elif number==67:
print(«Результат:36»)
elif number==68:
print(«Результат:36»)
elif number==69:
print(«Результат:36»)
#финальная консоль

Читайте также:  Html element name property

close=input(«Хотите продолжить?(Да/Нет)»)
if close==»Нет»:
print(«До свидания =(«)
exit()
elif close==»Да»:
вот здесь нужно добавить перезапуск

Я знаю что можно было побыстрее весь код обернуть, но как то вот так, с английским худо поэтому на русском (

Простой 1 комментарий

Источник

Supervisor. Настраиваем автоматический перезапуск скриптов

Александр Менщиков

Одной из важнейших задач при разработке серверных частей API или Ботов, обрабатывающих различные оповещения, является обеспечение их бесперебойной работы. Иными словами, необходимо автоматизированно произвести запуск всех необходимых скриптов при перезагрузке системы и перезапуск в случае ошибок и падений.

Одним из главных иструментов является supervisor.

Для установки достаточно набрать следующую команду в терминале (считаем что менеджер пакетов pip у вас уже уставнолен. Как это сделать читайте в статье Создаем бота для telegram).

Супервизор позволяет следить за состоянием приложений, останавливать, запускать и перезапускать их. Для начала нам нужно создать конфигурационный файл для вашей программы, где мы опишем основные правила перезапуска и логирования. По умолчанию можно воспользоваться файлом:

Удалим все содержимое и впишем следующий текст:

[program:github_server] command=python server.py directory=/var/www/codex.bot/ autorestart=true redirect_stderr=true stdout_logfile=/var/www/codex.bot/logs/app_sd.log stdout_logfile_maxbytes=50MB stdout_logfile_backups=50 stdout_capture_maxbytes=1MB stdout_events_enabled=false loglevel=warn

В примере мы указываем, что хотим обеспечить контроль скрипта server.py, находящегося в директории /var/www/codex.bot и уточняем еще пару настроек логирования ошибок. Если супервизор у вас еще не запущен, выполните команду:

Теперь можно попросить супервизор прочитать данные из конфига:

Для просмотра статуса запущенных процессов воспользуйтесь командой:

Процесс под названием “github_server” (название указывается в конфиге) будет находится в состоянии “STOPPED”.

Теперь в статусе будет отображено состояние “RUNNING”. Для остановки процесса можно пользоваться командой:

Наконец, если принудительно завершить процесс:

Он все равно будет перезапущен супервизором:

Состояние до завершения: github_server RUNNING pid 21755, uptime 0:03:57 Состояние после завершения: github_server RUNNING pid 21929, uptime 0:00:01

Видно, что сервер был перезапущен. Более подробно можно почитать в официальной документации.

Read more

We talk about interesting technologies and share our experience of using them.

Источник

Оцените статью