Меню

Питон выдает ошибку restart

I have a simple script I wrote, and when trying to run it (F5) , I get this msg:

================== RESTART: C:Users***Desktoptst.py ==================

I restarted the shell, reopened the script, but still, the same msg appears.
I use python 3.5.1 and I tried to simplify the script as much as possible, but I still get this result. Now my script is only one line with a simple print(1) command and I still get this msg.

Was there something wrong with the shell installation?

Terry Jan Reedy's user avatar

asked Jul 28, 2016 at 5:07

CIsForCookies's user avatar

CIsForCookiesCIsForCookies

11.7k10 gold badges56 silver badges114 bronze badges

8

I have a simple script I wrote, and when trying to run it (F5)

That’s the hotkey for IDLE to run a file. It is not ordering to do anything. It’s a log statement to explicitly declare that your namespace is being cleared and the file is going to be ran fresh again.

no, I didn’t tell it to restart

But you did… You pressed F5

answered Jul 28, 2016 at 5:18

OneCricketeer's user avatar

OneCricketeerOneCricketeer

169k18 gold badges124 silver badges230 bronze badges

5

The same thing is happening with my shell. In the older versions, this does not happen. I’ve also noticed that when I press Python 3.5.2 Module Docs, I have my Internet browser open up and I see my directory being displayed onscreen. It looks like:

C:UsersmycomputernameAppDataLocalProgramsPythonPython35-32DLLs.

Is that suppose to happen? Is that secured? I don’t know.

I’ve also found that this prints out whenever I «imported» something. So if I use an import command, and put it right before the line of my random name, it will print out that «RESTART» thing. It’s always at the beginning. Or what it reads as the beginning.

answered Aug 10, 2016 at 8:23

Ms. Lake's user avatar

CIsForCookies, my guess is that you don’t actually have a complete script; maybe you have just a function definition and you haven’t included a line to run that function. (I had this problem and then remembered to call the function I defined; the problem went away.)

answered Aug 28, 2019 at 14:32

Sakyataksis's user avatar

You may have made the same mistake as me and ran a program and then you wonder why RESTART is all that shows up. My program was working perfectly I just did not print anything or ask for any input so it ran and was done with the program and nothing showed up.

answered Nov 13, 2020 at 15:25

Watermelon 2000's user avatar

У меня есть простой скрипт, который я написал, и при попытке запустить его (F5) я получаю следующее сообщение:

================== RESTART: C: Users *** Desktop tst.py ================ ==

Я перезапустил оболочку, снова открыл сценарий, но все равно появляется то же сообщение. Я использую python 3.5.1, и я пытался максимально упростить сценарий, но я все еще получаю этот результат. Теперь мой скрипт — это всего одна строка с простой командой print(1), и я все еще получаю это сообщение.

Что-то не так с установкой оболочки?

3 ответа

Лучший ответ

У меня есть простой скрипт, который я написал, и при попытке запустить его (F5)

Это горячая клавиша для IDLE для запуска файла. Это не приказ делать что-либо. Это оператор журнала, который явно объявляет, что ваше пространство имен очищается и файл будет снова запущен заново.

нет я не сказал перезагружать

Но вы сделали … Вы нажали F5


1

cricket_007
28 Июл 2016 в 05:20

То же самое происходит с моей оболочкой. В старых версиях этого не происходит. Я также заметил, что когда я нажимаю Python 3.5.2 Module Docs, у меня открывается интернет-браузер, и я вижу, что мой каталог отображается на экране. Это выглядит как:

C : Users mycomputername AppData Local Programs Python Python35-32 библиотеки DLL .

Это должно произойти? Это обеспечено? Я не знаю.

Я также обнаружил, что это печатает всякий раз, когда я «импортировал» что-то. Поэтому, если я использую команду импорта и помещу ее прямо перед строкой моего произвольного имени, она выведет эту вещь «RESTART». Это всегда в начале. Или то, что читается как начало.


0

Ms. Lake
10 Авг 2016 в 08:51

CIsForCookies, я думаю, что у вас нет полноценного скрипта; возможно, у вас есть только определение функции, и вы не включили строку для запуска этой функции. (У меня была эта проблема, а затем я вспомнил, что вызвал определенную мной функцию; проблема ушла.)


0

Sakyataksis
28 Авг 2019 в 14:32

Обычно в режиме ожидания (если он не запущен с -n) выполняется код пользователя в подпроцессе пользователя. Строка RESTART означает, что подпроцесс был перезапущен. Независимо от того, как запускается Idle (без -n), это происходит либо при выборе Shell → Restart Shell Cntl + F6, либо в Run → Run Module F5.

RESTART также возникает, если пользовательский процесс вылетает из программы. Если вы запускаете Idle из командной строки (python -m idlelib или ... idlelib.idle в 2.x, там может появиться сообщение об ошибке, но это не происходит с вашей программой.

Я запустил вашу программу с помощью 3.4.3 после первой замены строки ввода конкретным назначением (которое вы должны были сделать перед публикацией)

x = list(reversed(range(1000)))

(Этот выбор является наихудшим вариантом для многих алгоритмов сортировки).

Я ничего не видел в командном окне, но видел сообщение Windows, которое python.exe прекратил работать. Поскольку Idle все еще работает, это относится к процессу ошибок.

Сокращение 1000000 до 10000 ничего не изменило. Выход из предисловия рекурсии в 1000 приводит к длительной трассировке.

Traceback (most recent call last):
File "C:Programspython34tem.py", line 33, in <module>
fun(L,L_,c)
File "C:Programspython34tem.py", line 29, in fun
return fun(x,lista,c)
....
File "C:Programspython34tem.py", line 29, in fun
return fun(x,lista,c)
File "C:Programspython34tem.py", line 18, in fun
for i in range(len(x)-1):
RuntimeError: maximum recursion depth exceeded in comparison

Уменьшение списка до размера 100 не изменило результат. У вас бесконечный цикл, который вам нужно предотвратить.

Вы код не похожи на версии quicksort, с которыми я знаком. Возможно, вам следует рассмотреть определение алгоритма.

Однако эта строка для j в диапазоне (i + 1, я + 2): выглядит как ошибка, когда она повторяется только один раз, с j = i+1. Как бы то ни было, программа работает одинаково, если вы замените ее на эту строку и разделите следующие строки.

В любом случае условие завершения x[i]<=x[j] and c==len(x)-2 не выполняется. Я предлагаю начать с коротким списком с помощью нескольких элементов и добавить от заявлений для печати в fun, чтобы увидеть, как значения отклоняются от того, что вы ожидаете. Вы также можете попробовать выполнить свой алгоритм вручную.

Уведомления

  • Начало
  • » Python для новичков
  • » Проблема при запуске программы в среде wingide-101-6.0.12-1

#1 Май 27, 2018 12:57:44

Проблема при запуске программы в среде wingide-101-6.0.12-1

Здравствуйте! Помогите, пожалуйста решить проблему (ОС Windows 8.1 x64): установил python-3.7.0a1-amd64, затем wingide-101-6.0.12-1. При запуске wingide-101-6.0.12-1 сообщений об ошибке нет. Пытаюсь запустить первую программу
print(“Test”, 2*2)
в Pithon shell появляется сообщение: Cannot execute: Use option -> Restart shell to launch shell . В меню Options выполнил restart. Результат тот же. Буду очень признателен за помощь в решении проблемы. Скриншот прилагаю.

Прикреплённый файлы:
attachment Скрин_1.jpg (105,7 KБ)

Офлайн

  • Пожаловаться

#2 Май 27, 2018 14:06:42

Проблема при запуске программы в среде wingide-101-6.0.12-1

У тебя в настройке проекта какой интерпретатор установлен? Лучше используй Wing Personal он бесплатен и более продвинутый чем 101.

С дураками и сектантами не спорю, истину не ищу.
Ели кому-то правда не нравится, то заранее извиняюсь.

Офлайн

  • Пожаловаться

#3 Май 27, 2018 17:07:14

Проблема при запуске программы в среде wingide-101-6.0.12-1

Спасибо за отклик! Попробовал, но результат тот же. Ничего страшного, попробую ещё что-нибудь придумать.

Офлайн

  • Пожаловаться

#4 Май 28, 2018 11:53:17

Проблема при запуске программы в среде wingide-101-6.0.12-1

Для всех, у кого сложилась аналогичная проблема: нестыковка произошла из-за интерпретатора python-3.7.0a1-amd64.exe, заменил на версию 3.6.5 и всё заработало.

Офлайн

  • Пожаловаться

  • Начало
  • » Python для новичков
  • » Проблема при запуске программы в среде wingide-101-6.0.12-1

Created on 2018-07-28 10:59 by Cross!Alex21, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (8) msg322542 — (view) Author: Aleksa Bulatovic (Cross!Alex21) Date: 2018-07-28 10:59
I was writing a code for my test in idle python.When i run the module it's just keeps restarting.
This is my code:

sins = 0
check = input()
if check == "check_sins":
        print(sins)
second = input("Ok,you can start when you are ready,type Im Ready! if you want to start the game")
print("Welcome to How smart are you test")
name = input("What's your name? ")
print(name)
if name == "Dimitrije":
    print("Nice to meet you Dimitrije")
start = input("Ready to start the test: ")
if start == "Yes":
    print("A) Gorillaz")
    print("B) Alvin and the chipmunks")
    print("C) Despacito 2")
    print("D) Who are you even")
    q1 = input("Which was the first animated band ever created? ")
    a1 = "A) Gorillaz"
    b1 = "B) Alvin and the chipmunks"
    c1 = "C) Despacito 2"
    d1 = "D) Who are you even"
    if q1 == "A" or q1 == "a":
        print("You are right,adding 10 sins for that")
        sins += 10
    else:
            sins = sins - 10
    print("A) Milan")
    print("B) ")
    print("")
    print("")
else:
    print(second)
    if start == "Im ready!":
        print("Ok,let's start")
    print(q1)
    print(a1)
    print(b1)
    print(c1)
    print(d1)
    if q1 == "A":
        print("You are right,adding 10 sins for that")
        sins = sins + 10
Note:I started learning python yesterday and sins are just a refrence of the youtube channel name called CinemaSins.So don't judge.
msg322606 — (view) Author: Jared (j-rewerts) * Date: 2018-07-29 03:26
First off, no judgment! :)

I just want to get some more details from you. 
1) How are you running your program?
2) How far into your program do you get?
3) What are you passing in as values for your Input() calls?
msg322614 — (view) Author: Aleksa Bulatovic (Cross!Alex21) Date: 2018-07-29 08:32
Im running as a idle python(when im in editor,i run the module)
I get like in 3 days(if you asked when did i get into the program,english is not my first language)
For my input calls i put a string so that player knows what to answer to.
I hope i answered your questions for details.(I don't understand some things when someone says like '	PyArg_ParseTupleAndKeywords' or something like that,im 12 year old so i don't understand some issues)
msg322630 — (view) Author: Steve Dower (steve.dower) * (Python committer) Date: 2018-07-29 11:23
Maybe you could describe what it looks like when it restarts? Or take a screenshot and share it so we can see what is happening?
msg322649 — (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2018-07-30 04:15
In IDLE, Run Module, F5, is a shortcut, in a sense, for saving the file to filename, switching to a terminal or console window, such as Command Prompt on Windows, and entering 'python -i filename'.  The -i means 'switch it interactive mode after running the file'.  When you are done, and close the window, you can switch back to the editor.

The IDLE Shell more-or-less simulates Python's interactive mode.  When you hit F5, a separator line is added, like 
=================== RESTART: F:Pythonatem.py =====================
to indicate that Shell reinitialized itself and is now running your program.  This is completely normal and intended.  When your program finishes, Shell will display '>>> '.

Please try to read the IDLE doc, which is available on the Help menu as 'IDLE Help'.  You can ask about using Python and IDLE on python-list.   Always mention the Python version and operating system you are using.

You program has a bug.  In the 'else' section, it tries to print q1 without q1 being defined.

If a program has a severe bug that caused the Python executing your code to crash, Shell will restart with a line that does not have a filename, like
======================== RESTART ========================
This is hard to bring about and is also not an IDLE bug.
msg322661 — (view) Author: Aleksa Bulatovic (Cross!Alex21) Date: 2018-07-30 09:15
Well the error looks like this

===== RESTART: F:Python Shell LearningGamesHow smart are you Test.py =====
i think it's normal but it won't show '>>> '.I will see what i can do,but thanks for some help.
msg322680 — (view) Author: Terry J. Reedy (terry.reedy) * (Python committer) Date: 2018-07-30 17:22
Again, that RESTART line is NOT an error.  IDLE's prompt is not displayed until your program is completely done.  It initially pauses on the second line 'check = input()', waiting for user input.

Start with a one-line file:

print('Hello to my game')

Run that and you will see the prompt.
msg322690 — (view) Author: Aleksa Bulatovic (Cross!Alex21) Date: 2018-07-30 20:25
Thanks Terry J. ReedyTerry.
History Date User Action Args 2022-04-11 14:59:03 admin set github: 78439 2018-07-30 20:25:48 Cross!Alex21 set messages:
+ msg322690 2018-07-30 17:22:15 terry.reedy set messages:
+ msg322680 2018-07-30 09:15:50 Cross!Alex21 set messages:
+ msg322661 2018-07-30 04:15:06 terry.reedy set status: open -> closed
type: behavior
messages:
+ msg322649

resolution: not a bug
stage: resolved

2018-07-29 11:23:01 steve.dower set nosy:
+ terry.reedy
messages:
+ msg322630

assignee: terry.reedy
components:
+ IDLE

2018-07-29 08:32:19 Cross!Alex21 set messages:
+ msg322614 2018-07-29 03:26:08 j-rewerts set nosy:
+ j-rewerts
messages:
+ msg322606 2018-07-28 10:59:29 Cross!Alex21 create

Работал на ноутбуке Samsung 300E5X-U02 (процессор Intel Pentium B960), Windows 10 x64. Программа на Python 2.7.6 x64, запускаю через Python IDLE, при помощи Selenium (webdriver = chromedriver) парсил сайты. Все работало без нареканий. Недавно купил другой ноутбук ACER Aspire E5-553G-15CK (процессор AMD A12 9700P), установил ту же Windows 10 x64, тот же Python 2.7.6 x64, но Python IDLE периодически начал самопроизвольно перезапускаться, причем, как оказалось, даже если программа выкинула ошибку и я не закрывал Python Shell, за ночь получается 3-4 перезапуска (сообщения о рестарте идут друг за другом). Аналогично на Python 2.7.12 x64 и на Python 3.5.2 x64. В чем может быть причина, неужели это из-за процессора?

=============================== RESTART: Shell ===============================
>>> 
=============================== RESTART: Shell ===============================
>>> 
=============================== RESTART: Shell ===============================
>>> 
=============================== RESTART: Shell ===============================
>>>

Всякий раз, когда я запускаю программу в Python Shell, я получаю строку с надписью RESTART: C:… $.

Перезапуск программы, использование программ, в которых раньше не возникало этой проблемы, и т. д., Похоже, ничего не дает. Заранее благодарю за любой совет!

Чем это вызвано?

Мутабельность и переработка объектов в Python

другой маршрут в Flask Python

другой маршрут в Flask Python

Flask — это фреймворк, который поддерживает веб-приложения. В этой статье я покажу, как мы можем использовать @app .route в flask, чтобы иметь другую…

14 Задание: Типы данных и структуры данных Python для DevOps

Python PyPDF2 - запись метаданных PDF

Переменные, типы данных и операторы в Python

Почему Python - идеальный выбор для проекта AI и ML


Ответы
1

Ответ принят как подходящий

Эта строка означает, что файл .py был выполнен в оболочке python.

Это оператор журнала, чтобы явно объявить, что ваше пространство имен очищается и файл снова будет запущен.

In simple words: The IDLE internally restarts itself before executing
your program, thus clearing all the information above so the variables
from earlier programs will not mess with your program

.

Другие вопросы по теме

When the python script crashes, the program is not running anymore, therefore the script cannot execute more lines of code.

You have 2 options:

  1. Make sure your python script doesn’t crash, which is very much recommended. You can do this by handling the exceptions thrown by your program.

Option 1

I assume you are new to python, so here is an example of a python script that handles an exception calls the same function again.

from time import sleep

def run_forever():
    try:
        # Create infinite loop to simulate whatever is running
        # in your program
        while True:
            print("Hello!")
            sleep(10)

            # Simulate an exception which would crash your program
            # if you don't handle it!
            raise Exception("Error simulated!")
    except Exception:
        print("Something crashed your program. Let's restart it")
        run_forever() # Careful.. recursive behavior
        # Recommended to do this instead
        handle_exception()

def handle_exception():
    # code here
    pass

run_forever()
  1. If you want to restart the python script you would need another python script (assuming you want to do this with python) that checks if the process is still alive and if not then run it again with python.

Option 2

This is the script that starts another python script called ‘test.py’ via the command python test.py.
Make sure you have the right file path, if you put the scripts in the same folder, you usually don’t need the full path and only the script name.

Notably, make sure that command ‘python‘ is recognized by your system, it could in some cases by ‘python3’

script_starter.py

from subprocess import run
from time import sleep

# Path and name to the script you are trying to start
file_path = "test.py" 

restart_timer = 2
def start_script():
    try:
        # Make sure 'python' command is available
        run("python "+file_path, check=True) 
    except:
        # Script crashed, lets restart it!
        handle_crash()

def handle_crash():
    sleep(restart_timer)  # Restarts the script after 2 seconds
    start_script()

start_script()

In case you are interested in the code I used for the test file: ‘test.py’, I post it here.

test.py

from time import sleep
while True:
    sleep(1)
    print("Hello")
    raise Exception("Hello")

Here is a simple trick that I used to restart my python script after unhandled exception.

Let’s say I have this simple script called test.py that I want to run forever. It will just wait 2 seconds and throw an error.

import time time.sleep(2) raise Exception("Oh oh, this script just died")

Code language: JavaScript (javascript)

I use the following script called forever in the same directory:

#!/usr/bin/python from subprocess import Popen import sys filename = sys.argv[1] while True: print("nStarting " + filename) p = Popen("python " + filename, shell=True) p.wait()

Code language: JavaScript (javascript)

It uses python to open test.py as a new subprocess. It does so in an infinite while loop, and whenever test.py fails, the while loop restarts test.py as a new subprocess.

I’ll have to make the forever script executable by running chmod +x forever. Optionally forever script can be moved to some location in the PATH variable, to make it available from anywhere.

Next, I can start my program with:

./forever test.py

Which will result in the following output:

Starting test.py Traceback (most recent call last): File "test.py", line 4, in <module> raise Exception("Oh oh, this script just died") Exception: Oh oh, this script just died Starting test.py Traceback (most recent call last): File "test.py", line 4, in <module> raise Exception("Oh oh, this script just died") Exception: Oh oh, this script just died Starting test.py

Code language: JavaScript (javascript)

As you can tell, this script will run repeatedly, until it is killed with ctr+c.

I am running my Python script in the background in my Ubuntu machine (12.04) like this —

nohup python testing.py > test.out &

Now, it might be possible that at some stage my above Python script can die for whatever reason.

So I am thinking to have some sort of cron agent in bash shell script which can restart my above Python script automatically if it is killed for whatever reason.

Is this possible to do? If yes, then what’s the best way to solve these kind of problem?

UPDATE:

After creating the testing.conf file like this —

chdir /tekooz
exec python testing.py
respawn

I ran below sudo command to start it but I cannot see that process running behind using ps ax?

root@bx13:/bezook# sudo start testing
testing start/running, process 27794
root@bx13:/bezook# ps ax | grep testing.py
27806 pts/3    S+     0:00 grep --color=auto testing.py

Any idea why px ax is not showing me anything? And how do I check whether my program is running or not?

This is my python script —

#!/usr/bin/python
while True:
    print "Hello World"
    time.sleep(5)

asked Jan 5, 2014 at 7:33

arsenal's user avatar

arsenalarsenal

2,95317 gold badges43 silver badges49 bronze badges

On Ubuntu (until 14.04, 16.04 and later use systemd) can use upstart to do so, better than a cron job. You put a config setup in /etc/init and make sure you specify respawn

It could be a minimal file /etc/init/testing.conf (edit as root):

chdir /your/base/directory
exec python testing.py
respawn

And you can test with /your/base/directory/testing.py:

from __future__ import print_function

import time

with open('/var/tmp/testing.log', 'a') as fp:
    print(time.time(), 'done', file=fp)
    time.sleep(3)

and start with:

sudo start testing

and follow what happens (in another window) with:

tail -f /var/tmp/testing.log

and stop with:

sudo stop testing

You can also add [start on][2] to have the command start on boot of the system.

answered Jan 5, 2014 at 7:59

Zelda's user avatar

ZeldaZelda

5,9601 gold badge20 silver badges27 bronze badges

6

You could also take a more shell oriented approach. Have your cron look for your script and relaunch it if it dies.

  1. Create a new crontab by running crontab -e. This will bring up a window of your favorite text editor.

  2. Add this line to the file that just opened

    */5 * * * * pgrep -f testing.py || nohup python /home/you/scripts/testing.py > test.out
    
  3. Save the file and exit the editor.

You just created a new crontab which will be run every 5 minutes and launch your script unless it is already running. See here for a nice little tutorial on cron. The official Ubuntu docs on cron are here.

The actual command being run is pgrep which searches running processes for the string given in the command line. pgrep foo will search for a program named foo and return its process identifier. pgrep -f makes it search the entire command line used to launch the program and not only the program name (useful because this is a python script).

The || symbol means «do this if the previous command failed». So, if your script is not running, the pgrep will fail since it will find nothing and your script will be launched.

answered Jan 5, 2014 at 9:24

terdon's user avatar

terdonterdon

226k62 gold badges423 silver badges632 bronze badges

14

You shouldn’t really use this for production, but you could:

#!/bin/sh

while true; do
  nohup python testing.py >> test.out
done &

If, for any reason, python process exits, the shell loop will continue and restart it, appending to the .out file as desired. Nearly no overhead and takes very little time to set up.

answered Jan 5, 2014 at 12:17

K3---rnc's user avatar

K3—rncK3—rnc

3,0241 gold badge16 silver badges9 bronze badges

You can have the testing program redirect the output using a commandline option
and then use a simple python script to restart the program indefinitely:

import subprocess

while True:
    try:
        print subprocess.check_output(['python', 'testing.py'])
    except KeyboardInterrupt:
        break

you can put this program in the background, and once you want to stop just pull it into the foreground and kill it.

answered Jan 5, 2014 at 8:16

Anthon's user avatar

AnthonAnthon

76.9k42 gold badges159 silver badges217 bronze badges

There are a number of ways to monitor and respawn processes under UNIX/Linux. One of the oldest is a «respawn» entry in /etc/inittab … if you’re using the old SysV init system. Another method is to use the supervisor daemon from DJ Bernstein’s daemontools package. Other options are to use features in Ubuntu upstart … or systemd or others.

But you can look at alternatives init and in the Python code for Pardus: mudur daemon in particular.

If you decide to go with a cron job (and PID file handling) then consider reading this PEP 3143 and perhaps using its reference implementation.

As I alluded to in my other comments, robust PID file handling is tricky. It’s prone to races and corner cases. It gets trickier if there’s any chance that your PID file ends up on an NFS or other networked filesystem (some of the atomicity guarantees you get with the file handling semantics on proper local UNIX/Linux filesystems go away on some versions and implementations of NFS, for example). Also the semantics around file locking under UNIX can be tricky. (Does an flock or fcntl lock get released promptly, in your target OS, when the process holding it is killed with SIGKILL, for example?).

answered Jan 5, 2014 at 7:58

Jim Dennis's user avatar

Jim DennisJim Dennis

6002 silver badges11 bronze badges

You can also use monit Or Process monitoring with ps-watcher

Monit is an open source utility for managing and monitoring,
processes, programs, files, directories and filesystems on a UNIX
system. Monit conducts automatic maintenance and repair and can
execute meaningful causal actions in error situations.

Here is example for your scenario:

check process myprocessname
        matching "myprocessname"
        start program = "nohup /usr/bin/python /path/testing.py > /tmp/test.out &"
        stop program = "/usr/bin/killall myprocessname"

Take look at monit examples

answered Jan 5, 2014 at 9:43

Rahul Patil's user avatar

Rahul PatilRahul Patil

23.5k25 gold badges79 silver badges95 bronze badges

You need a supervisor, you can use supervisor. It is python based supervisor, therefore easy to modify if you need to.

Control is with files with .ini file syntax.

answered Jan 5, 2014 at 10:59

user41123's user avatar

user41123user41123

1942 silver badges6 bronze badges

Terdon’s answer, did not work for me, because
pgrep -f testing.py was never ‘failing’. It would grab the pid for the cron job (because of the -f option). However, without the -f option pgrep won’t find testing.py because there’s no process called testing.py.

My solution to this was to change

pgrep -f testing.py

to

pgrep -f testing.py | pgrep python

this means the full crontab job would be:

*/5 * * * * pgrep -f testing.py | pgrep python || nohup python /home/you/scripts/testing.py > test.out

Stephen Rauch's user avatar

answered Jun 15, 2017 at 20:00

Matt's user avatar

In my case, as a quick-fix, I wanted to keep my program running when it exited with en error or it was killed.
On the other hand, I wanted to stop the execution when the program terminated correctly (return code = 0)

I have tested it on Bash. It should work fine in any other shell

#!/bin/sh

echo ""
echo "Use: $0 ./instagram.py"
echo ""

echo "Executing $1 ..."

EXIT_CODE=1
(while [ $EXIT_CODE -gt 0 ]; do
    $1
    # loops on error code: greater-than 0
    EXIT_CODE=$?
done)

answered Dec 27, 2018 at 12:53

user9869932's user avatar

For terdon’s answer, pgrep -f testing.py will never return false according to the comments in here:

I think the issue is that cron spawns a shell to run your command, and the arguments of that shell are matched by pgrep since you are using -f

For Matt’s answer, pgrep -f testing.py is useless since pgrep python matches any running Python script. So if two Python script cronjob, the second cronjob will never run.

And then I found the solution to solve pgrep -f testing.py in the comment here: https://askubuntu.com/questions/1014559/running-pgrep-in-a-crontab?noredirect=1&lq=1

My cron for running two Python scripts:

* * * * * pgrep -f '^/usr/bin/python36 /home/ec2-user/myscript1.py' || nohup /usr/bin/python36 /home/ec2-user/myscript1.py

0 * * * * pgrep -f '^/usr/bin/python36 /home/ec2-user/myscript2.py' || nohup /usr/bin/python36 /home/ec2-user/myscript2.py

Rui F Ribeiro's user avatar

Rui F Ribeiro

54.8k26 gold badges143 silver badges220 bronze badges

answered Mar 8, 2019 at 19:28

Frank's user avatar

FrankFrank

1012 bronze badges

In Ubuntu this works for me thanks to --wait

#!/bin/bash

while :
do
  sleep 5
  gnome-terminal --wait -- sh -c "python3 myscript.py 'myarg1'"
done

answered Nov 17, 2020 at 20:44

Chris's user avatar

ChrisChris

1011 bronze badge

There’s a Python module for that, forever.

The advantage being, hopefully, in using the same language for both the code and the watchdog. If it needs to be improved, one can find it in

cd $(python -c "import site; print(site.getusersitepackages())")

I’d install it with

python -mpip install --user --upgrade forever

and later use it with

python -mforever.run -t 9 -i 9 python script-to-watch.py

answered Feb 12, 2022 at 12:06

ArtemGr's user avatar

1

Sometimes, you may wish to check within a script when a configuration file or the script itself changes, and if so, then automatically restart the script. In this post, you will see a way of doing this in Python.

Consider the following scenario. You have a Python script that runs as a daemon and regularly performs the prescribed tasks. Examples may be a web server, a logging service, and a system monitor. When the script starts, it reads its configuration from a file, and then enters an infinite loop. In this loop, it waits for inputs from the environment and acts upon them. For example, a web server may react to a request for a page, which results into sending a response to the user.

From time to time, it may be necessary to restart the script. For example, if you fix a bug in it or change its configuration. One way of doing so is to kill the script and run it again. However, this requires manual intervention, which you may forget to do. When you fix a vulnerability in the script, you want to be sure that you do not forget to restart the script. Otherwise, someone may exploit the vulnerability if you did not restart the script. It would be nice if there existed a way of restarting the script within itself after it detected that its sources or a configuration file changed. In the rest of this post, we will show such a way.

For the purpose of the present post, let us assume that the script has the following structure:

# Parse the arguments and configuration files.

while True:
    # Wait for inputs and act on them.
    # ...

That is, it processes the arguments and loads the configuration from the configuration files. After that, the script waits for inputs and processes them in an infinite loop.

Next, we describe how to watch files for changes. After that, we show how to restart the script.

Checking Watched Files For Changes

First, we define the paths to the files whose change we want to watch:

WATCHED_FILES = [GLOBAL_CONFIG_FILE_PATH, LOCAL_CONFIG_FILE_PATH, __file__]

We watch the global configuration file, the local configuration file, and the script itself, whose path can be obtained from the special global variable __file__. When the script starts, we get and store the time of the last modification of these files by using os.path.getmtime():

from os.path import getmtime

WATCHED_FILES_MTIMES = [(f, getmtime(f)) for f in WATCHED_FILES]

Then, we add a check if any of these files have changed into the main loop:

while True:
    for f, mtime in WATCHED_FILES_MTIMES:
        if getmtime(f) != mtime:
            # Restart the script.

    # Wait for inputs and act on them.
    # ...

If either of the files that we watch has changed, we restart the script. The restarting is described next.

Restarting the Script

We restart the script by utilizing one of the exec*() functions from the os module. The exact version and arguments depend on how you run the script. For example, on Linux or Mac OS, you can make the file executable by putting the following line to the top of the file

#!/usr/bin/env python

and executing

$ chmod a+x daemon.py

Then, you can run the script via

$ ./daemon.py

In such a situation, to restart the script, use the following code:

os.execv(__file__, sys.argv)

Otherwise, when you run the script via

$ python daemon.py

use this code:

os.execv(sys.executable, ['python'] + sys.argv)

Either way, do not forget to import the sys module:

import sys

To explain, the arguments of os.execv() are the program to replace the current process with and arguments to this program. The __file__ variable holds a path to the script, sys.argv are arguments that were passed to the script, and sys.executable is a path to the Python executable that was used to run the script.

The os.execv() function does not return. Instead, it starts executing the current script from its beginning, which is what we want.

Concluding Remarks

If you use the solution above, please bear in mind that the exec*() functions cause the current process to be replaced immediately, without flushing opened file objects. Therefore, if you have any opened files at the time of restarting the script, you should flush them using f.flush() or os.fsync(fd) before calling an exec*() function.

Of course, the presented solution is only one of the possible ways of restarting a Python script. Depending on the actual situation, other approaches, like killing the script externally and starting it afterwards, may be more suitable for you. Moreover, there exist other methods of checking whether a watched file has changed and acting upon such a change. If you know of another way of restarting a Python program within itself, please share it by posting a comment.

Complete Source Code

The complete source code for this post is available on GitHub.

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

import numpy as np

def main():
    np.load('File.csv')

for i in range(1, 10):
    try:
        main()
    except Exception as e:
        print e
        print 'Restarting!'
        main()

3 ответа

Лучший ответ

Чтобы сделать это внутри Python, используйте try/except соответственно:

import numpy as np

def main():
    np.load('File.csv')

for i in range(1, 10):
    try:
        main()
    except Exception as e:
        print e
        print 'Restarting!'
        continue
    else:
        break

Для простых инструкций это работает, но если ваш код становится более сложным, помещение всей функции main() в блок try/except может скрыть исключения и затруднить отладку вашей программы. Таким образом, я бы порекомендовал обработать перезапуск вне питона, например в скрипте bash.


2

dron22
8 Апр 2016 в 13:53

Вы можете очень хорошо использовать рекурсивную функцию здесь для автоматического перезапуска кода. используйте setrecursionlimit (), чтобы определить количество попыток следующим образом:

import numpy as np
import sys
sys.setrecursionlimit(10)  # set recursion depth limit


def main():
    try:
        a = np.load('file.csv')
        if a:
            return a
    except Exception as e:
        return main()

result = main()
print result

Надеюсь это поможет :)


1

hemraj
8 Апр 2016 в 14:16

Для чего-то подобного (подключение к веб-странице) часто лучше устанавливать верхний предел на основе времени, а не количества попыток подключения. Так что используйте цикл while:

import numpy as np
import time

def main():
    np.load('file.csv')

start = time.time()
stop = start + 5
attempts = 0
result = 'failed'

while True:
    if time.time()<stop:
        try:
            main()
        except Exception as e:
            attempts += 1
            print e
            time.sleep(0.1) # optional
            print 'Restarting!'
            continue
        else:
            result = 'succeeded'
    print 'Connection %s after %i attempts.' % (result, attempts)
    break

Необязательно: я включил паузу в 100 мс после каждой неудачной попытки. Это может помочь с установлением соединения иногда.

Затем оберните все это в функцию, которую вы можете использовать в будущем для других проектов:

# retry.py

import time

def retry(f, seconds, pause = 0):
    start = time.time()
    stop = start + seconds
    attempts = 0
    result = 'failed'

    while True:
        if time.time()<stop:
            try:
                f()
            except Exception as e:
                attempts += 1
                print e
                time.sleep(pause)
                print 'Restarting!'
                continue
            else:
                result = 'succeeded'
        print '%s after %i attempts.' % (result, attempts)
        break

Теперь просто сделай это:

import numpy as np
from retry import retry

def main():
    np.load('file.csv')

retry(main, 5, 0.1)

Процедура тестирования:

class RetryTest():
    def __init__(self, succeed_on = 0, excp = Exception()):
        self.succeed_on = succeed_on
        self.attempts = 0
        self.excp = excp
    def __call__(self):
        self.attempts += 1
        if self.succeed_on == self.attempts:
            self.attempts = 0
        else:
            raise self.excp

retry_test1 = RetryTest(3)
retry(retry_test1, 5, 0.1)
# succeeded after 3 attempts.
retry_test2 = RetryTest()
retry(retry_test2, 5, 0.1)
# failed after 50 attempts.


1

Rick supports Monica
8 Апр 2016 в 23:32

How do you make a python program automatically restart itself? So let’s say there is a really simple program like:

var = input("Hi! I like cheese! Do you like cheese?").lower()
if var == "yes":
    print("That's awesome!")

Now, in a Python Shell, you would have to press either the Run button and then ‘Run Module (F5)’ or just the F5 key on your keyboard. That is the first time you run it. When the program ended, you would go back to your Cheese.py file and then press F5 to run the program again.

Everybody with me here?
OK, so my question is, how do you make the program restart itself automatically without you having to manually do it?

martineau's user avatar

martineau

117k25 gold badges161 silver badges290 bronze badges

asked Mar 15, 2016 at 17:42

DavidEclipse's user avatar

3

It depends on what you mean by «restart itself.» If you just want to continuously execute the same code, you can wrap it in a function, then call it from within a while True loop, such as:

>>> def like_cheese():
...     var = input("Hi! I like cheese! Do you like cheese?").lower()  # Corrected the call to `.lower`.
...     if var == "yes":
...         print("That's awesome!")
...
>>> while True:
...     like_cheese()
...
Hi! I like cheese! Do you like cheese?yes
That's awesome!
Hi! I like cheese! Do you like cheese?yes
That's awesome!

If you want to actually restart the script you can execute the script again, replacing the current process with the new one by doing the following:

#! /bin/env python3
import os
import sys

def like_cheese():
    var = input("Hi! I like cheese! Do you like cheese?").lower()
    if var == "yes":
        print("That's awesome!")

if __name__ == '__main__':
    like_cheese()
    os.execv(__file__, sys.argv)  # Run a new iteration of the current script, providing any command line args from the current iteration.

This will continuously re-run the script, providing the command line arguments from the current version to the new version. A more detailed discussion of this method can be found in the post «Restarting a Python Script Within Itself» by Petr Zemek.

One item that this article notes is:

If you use the solution above, please bear in mind that the exec*()
functions cause the current process to be replaced immediately,
without flushing opened file objects. Therefore, if you have any
opened files at the time of restarting the script, you should flush
them using f.flush() or os.fsync(fd) before calling an exec*()
function.

answered Mar 15, 2016 at 17:55

Deacon's user avatar

DeaconDeacon

3,51529 silver badges52 bronze badges

1

or you can try

$ chmod a+x "name".py

Then, you can run the script via

$ ./daemon.py

In such a situation, to restart the script, use the following code:

os.execv(__file__, sys.argv)

Otherwise, when you run the script via

$ python daemon.py

use this code:

os.execv(sys.executable, ['python'] + sys.argv)

Either way, do not forget to import the sys module

L_J's user avatar

L_J

2,29510 gold badges24 silver badges28 bronze badges

answered Jul 14, 2018 at 16:32

user10081708's user avatar

0

I use terminal on my Mac to re-start some of my python scripts with the function below.

import subprocess  
def run_again(cmd):
    subprocess.call(["bash", "-c", "source ~/.profile; " + cmd])  

Note: Don’t forget the space character after «profile;» or the function may fail silently!

Then at the bottom of my script to be re-started:

if some_condition:  
    run_again("python my_script.py %s" % my_new_arguments)  

For the original question about the cheese script:

if var != 'yes':  
    run_again("python my_cheese_script.py")  

answered Oct 13, 2017 at 18:13

exbctel's user avatar

exbctelexbctel

1951 silver badge9 bronze badges

You can just use a shell script like test.sh and make sure in your linux terminal you chmod +x test.sh

As for the code:

#!/bin/bash

while :
do
  sleep 5
  gnome-terminal --wait -- sh -c "python3 myscript.py 'myarg1'"
done

answered Nov 17, 2020 at 20:46

Chris's user avatar

ChrisChris

17.2k15 gold badges56 silver badges76 bronze badges

You can wrap something in while True: to make it execute repeatedly, as True will always evaluate to True, like this:

while True:
    var = input("Hi! I like cheese! Do you like cheese?").lower() # <-- You had missed parentheses here        
    if var == "yes":
        print("That's awesome!")

There’s another issue with your code though; you haven’t called lower by putting parentheses after it.

answered Mar 15, 2016 at 17:44

Aaron Christiansen's user avatar

7

How do you make a python program automatically restart itself? So let’s say there is a really simple program like:

var = input("Hi! I like cheese! Do you like cheese?").lower()
if var == "yes":
    print("That's awesome!")

Now, in a Python Shell, you would have to press either the Run button and then ‘Run Module (F5)’ or just the F5 key on your keyboard. That is the first time you run it. When the program ended, you would go back to your Cheese.py file and then press F5 to run the program again.

Everybody with me here?
OK, so my question is, how do you make the program restart itself automatically without you having to manually do it?

martineau's user avatar

martineau

117k25 gold badges161 silver badges290 bronze badges

asked Mar 15, 2016 at 17:42

DavidEclipse's user avatar

3

It depends on what you mean by «restart itself.» If you just want to continuously execute the same code, you can wrap it in a function, then call it from within a while True loop, such as:

>>> def like_cheese():
...     var = input("Hi! I like cheese! Do you like cheese?").lower()  # Corrected the call to `.lower`.
...     if var == "yes":
...         print("That's awesome!")
...
>>> while True:
...     like_cheese()
...
Hi! I like cheese! Do you like cheese?yes
That's awesome!
Hi! I like cheese! Do you like cheese?yes
That's awesome!

If you want to actually restart the script you can execute the script again, replacing the current process with the new one by doing the following:

#! /bin/env python3
import os
import sys

def like_cheese():
    var = input("Hi! I like cheese! Do you like cheese?").lower()
    if var == "yes":
        print("That's awesome!")

if __name__ == '__main__':
    like_cheese()
    os.execv(__file__, sys.argv)  # Run a new iteration of the current script, providing any command line args from the current iteration.

This will continuously re-run the script, providing the command line arguments from the current version to the new version. A more detailed discussion of this method can be found in the post «Restarting a Python Script Within Itself» by Petr Zemek.

One item that this article notes is:

If you use the solution above, please bear in mind that the exec*()
functions cause the current process to be replaced immediately,
without flushing opened file objects. Therefore, if you have any
opened files at the time of restarting the script, you should flush
them using f.flush() or os.fsync(fd) before calling an exec*()
function.

answered Mar 15, 2016 at 17:55

Deacon's user avatar

DeaconDeacon

3,51529 silver badges52 bronze badges

1

or you can try

$ chmod a+x "name".py

Then, you can run the script via

$ ./daemon.py

In such a situation, to restart the script, use the following code:

os.execv(__file__, sys.argv)

Otherwise, when you run the script via

$ python daemon.py

use this code:

os.execv(sys.executable, ['python'] + sys.argv)

Either way, do not forget to import the sys module

L_J's user avatar

L_J

2,29510 gold badges24 silver badges28 bronze badges

answered Jul 14, 2018 at 16:32

user10081708's user avatar

0

I use terminal on my Mac to re-start some of my python scripts with the function below.

import subprocess  
def run_again(cmd):
    subprocess.call(["bash", "-c", "source ~/.profile; " + cmd])  

Note: Don’t forget the space character after «profile;» or the function may fail silently!

Then at the bottom of my script to be re-started:

if some_condition:  
    run_again("python my_script.py %s" % my_new_arguments)  

For the original question about the cheese script:

if var != 'yes':  
    run_again("python my_cheese_script.py")  

answered Oct 13, 2017 at 18:13

exbctel's user avatar

exbctelexbctel

1951 silver badge9 bronze badges

You can just use a shell script like test.sh and make sure in your linux terminal you chmod +x test.sh

As for the code:

#!/bin/bash

while :
do
  sleep 5
  gnome-terminal --wait -- sh -c "python3 myscript.py 'myarg1'"
done

answered Nov 17, 2020 at 20:46

Chris's user avatar

ChrisChris

17.2k15 gold badges56 silver badges76 bronze badges

You can wrap something in while True: to make it execute repeatedly, as True will always evaluate to True, like this:

while True:
    var = input("Hi! I like cheese! Do you like cheese?").lower() # <-- You had missed parentheses here        
    if var == "yes":
        print("That's awesome!")

There’s another issue with your code though; you haven’t called lower by putting parentheses after it.

answered Mar 15, 2016 at 17:44

Aaron Christiansen's user avatar

7

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Питать трепет лексическая ошибка
  • Питон выдает ошибку invalid syntax