Из соображений эффективности модуль загружается только один раз за сеанс интерпретатора. Это хорошо для определений функций и классов, которые обычно составляют основную часть содержимого модуля. Но модуль также может содержать исполняемые операторы, обычно для инициализации.
Имейте в виду, что эти инструкции будут выполняться только при первом импорте модуля.
a = [100, 200, 300] print(‘a =’, a)
>>> import mod a = [100, 200, 300] >>> import mod >>> import mod >>> mod.a [100, 200, 300]
Встроенная функция print() не выполняется при последующих импортах.
Если в модуль вносятся изменения то модуль нужно перезагружать, что бы изменения вступили в силу. Для этого нужно либо перезапустить интерпретатор, либо использовать функцию importlib.reload() из модуля importlib :
>>> import mod a = [100, 200, 300] >>> import mod >>> import importlib >>> importlib.reload(mod) a = [100, 200, 300]
Перезагрузка модуля импортированного конструкцией from import .
from module> import name> # перезагрузка модуля import importlib, sys name = importlib.reload(sys.modules[‘module’]).name
- ОБЗОРНАЯ СТРАНИЦА РАЗДЕЛА
- Спецификация инструкции import.
- Определение модуля и его импорт.
- Конструкция импорта import modulle as name.
- Конструкция импорта from modulle import names.
- Конструкция импорта from modulle import name as alt_name.
- Как Python ищет импортируемый модуль
- Список имен, определенных в модуле Python.
- Выполнение модуля как скрипта.
- Перезагрузка модуля.
- Пакеты модулей.
- Файл пакета __init__.py.
- Переменная __all__ в пакетах и модулях.
- Переменная пакета __path__.
- Относительный импорт пакетов.
- Вложенные подпакеты.
- Пространства имен пакета.
- Настройка доступа к атрибутам модуля.
Источник: docs-python.ru
Информационные веб-панели и сайты с помощью Python Streamlit
Как перезапустить программу в 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.
Petr Zemek
Links
Categories
Restarting a Python Script Within Itself
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.
Как перевести текст в речь на python? #pycharm #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:
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:
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() :
Then, we add a check if any of these files have changed into the main loop:
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
Then, you can run the script via
In such a situation, to restart the script, use the following code:
Otherwise, when you run the script via
Either way, do not forget to import the sys module:
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.
29 Comments
This looks to be exactly what I am looking for.
I am very new to Python though so I am struggling figuring out how exactly to implement this.
I have a cron job that runs (lets call it program A) every night at midnight and goes to a webservice and checks to see if i have updated my code to my program (lets call it program B). If I have, it downloads the code and overwrites my program B code. Until know I couldn’t get program A to restart program B. So I set up a cron job that just reboots the PI every night. I don’t like this and would really like Program B to pick up the change and restart itself only if there has been a change. I am struggling on where to put this while loop in my code.
lets say i have a stop watch program that essentially shows a clock and a stop watch at the same time. Its always waiting on external inputs from GPIO to start and stop the stop watch and record their times. I tried putting your loop at the top and the bottom but my code either goes into an infinite loop or doesn’t display the main program. Any advice you could give would be appreciated.
You have to put the checking and restarting into a place that is periodically executed. For example, in a Tk application, this can be done by using root.after() as follows:
Just save the code into a file, make the file executable, and run it. Then, whenever you modify the file (its mtime attribute is changed), the application is automatically restarted. You can try it by yourself: run the application, modify the file in a text editor, and after at most two seconds, the application should be restarted.
But what if I accidentally introduce an error in the new version of this .py file? I would want the old version to keep on running (and output the error), and *try* restarting again when the file is next updated.
Your solution would have to be manually restarted after the problem is fixed.
I’m running a script on a beaglebone black with debian
Here is the part that gets the error.
this is the error
PS. I guess I need to figure out how to post a code block
thanks
bill
Hi Bill! Make sure that your script is executable, i.e. do
Then, the code you posted should work (I tested it).
Hi. Once I make the python file executable I got a new error:
I’ve checked and tried some shebangs but nothing works.
I don’t know what os.execv(__file__, sys.argv) exacly does, but seems a popen command at all.
This is what i did to relaunch the script:
Python script calling relaunch will launch itself again. I’m sure this solution do not cover memory handling or other aspects, but I need the script reloading at any cost
Hi erm3nda. To fix the Exec format error , put the following line to the top of the file:
This line informs the system to run the script in Python. When this line is not present, the system does not know how to execute the script when it is relaunched.
Also, what you are doing is blocking your script with an error and launching a new instance within that.
An easy way to restart the Python Shell programmatically is as follows
That was one way I found.
I saw that I tried some shebangs and still doesn’t work.
This time im working on a Windows machine and shebang does exactly nothing on it.
I’ve checked .py assoc with pythonw.exe instead python.exe and still doesn’t work.
I’m really stucked with that because that would be dead simple and is not.
Another way would be to create a simple Launcher just for that.
Nice code, just what I was looking for. Thanks!
What if the new script does eventually not work as expected and you revert back to the backed-up original? In that case
prevents the restart because the backup file has a mtime that is < than the mtime of the running script.
I would say: use
Yes, you are right, != is better. I have updated the code. Thanks!
2 things to remark: First of all, your code runs flawlessly unter Python 3 as well. Just use
as interpreter description (I assume it is installed…). Secondly, you can check every single file you want. Just use
Just for the beginners who don’t know – like me. (Trial and error – method…)
I also got the same problem.
It seems that __file__ refers to the compiled bytecode file with .pyc instead of the original .py.
Does this break the os.exec statement when trying to exec the bytecode directly?
Here’s my solution. It can relaunch the file even after you introduced errors.
man i will take back this
You have any idea what kind of problem is there?
If you are running on Linux/MacOS, make sure that your script is executable, i.e. do
When it complains about Exec format error , make sure that you have the following line at the beginning of the file:
Alternatively (or when you are on Windows), try changing the os.execv() line from
Man thanks for your quickly respond.
I am running on Ubuntu 14.04.
I try both of your solutions but nothing change.
You have any other idea?
From the traceback
it seems that you did not change the name of the file in your script. Try changing the line
and run the script via
thnx man… i see it and i fixed it. Now, the script run ok… i don’t run script via
but with the previous method
Great! I’m glad I could help.
Excellent….
Simply this was excellent.I went on finding for days to make a restart method for my GUI brain game.I found no way.But simply two lines from your dictums helped me out.
This is perfect. Thank you much….
I’ve put it in my excepthook function, adding the feature to control how many times should it be restarted before stopping it. Maybe this could be useful
it’s a big help to me , thanks a lot
Hi, thanks a lot for sharing this, it helped me a lot. At the same time, I have encountered some issues with it as well, wondering if you could help me. I created a button with a tkinter gui, when I press the button, it would run the code
. It worked perfectly for the first time, but when I press the same button on the restarted tkinter gui, the gui was closed (which is good), the new one did not show up. Within the console, it did not show anything, it was still recognized as the program is running i guess. Which made me press “control c” to interrupt it, then it says
Fatal Python error: Py_Initialize: can’t initialize sys standard streams
Do you have any ideas? Than you so much!
Ha! I have managed to restart the program in another way, but I think its a way that everybody knows.
I simply just use the following code.
I know it is like a “primary school” stuff, but it worked for me well, thanks anyways.
Restart your python program.
This snippet defines a function restart_program() which restarts your python program from within your python program.
Cool thanks!
Simple and elegant
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.
Wow thanks so much!
This just restarts the shell
How do i get it to run the program again?
Any help greatly appreciated
This just restarts the shell
are you using idle ? another ide ?
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.
Как запустить код заново в 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 fn Спасибо что посмотрел до конца))) ‘ )
time.sleep(15)
elif exit == ‘f’:
SystemExit(1)
#не угадал
elif random != number:
b = input( ‘Вы не угадали(( Может попробуем снова ? (да, нет) :’ )
Похожие публикации:
- Как поставить бота на хостинг discord
- Как сбросить пароль в линукс минт
- Как сделать круглую кнопку в tkinter
- Js как сохранить данные в файл
Источник: amdy.su
Python-сообщество
- Начало
- » Python для новичков
- » Это правда так сложно перезагрузить программу в Python?
#1 Фев. 2, 2021 21:08:39
Это правда так сложно перезагрузить программу в Python?
Я новичок в питоне, в детстве интересовался только бейсиком, немного программировал на нем и на лингвистически похожих языках или в программах, поэтому питон мне исключительно неинтуитивен по всему, что возможно.
Я так сяк написал на нем простую программку для работы моих майнеров, которая регулирует их поведение в зависимости от условий рынка. Проблема та, что время от времени сайт, с которого я получаю данные либо виснет, либо дает какие-то неправильные данные, и программа останавливается и выходит. Я ее вручную перезапускаю, и опять несколько часов все нормально.
Я часа 3 провел гуугля как можно автоматически сделать перезапуск, но ума сделать что-то рабочее мне не получается. Углубляться в то, почему и какие там ошибки вылетают, опять же, я на данный момент не хочу, так как банальный перезапуск программы все решает.
Неужели так сложно перезапустить программу, то, что в некоторых других оболочках можно было сделать простой галочкой или парой строк?
Питон на Pycharm на винде 10.
Посоветуйте простое решение.
Отредактировано Renaldas (Фев. 2, 2021 21:09:24)
#2 Фев. 2, 2021 23:38:16
Это правда так сложно перезагрузить программу в Python?
Тебе надо написать второй скрипт B, который запускает первый скрипт A и следит за ним. Если скрипт A выпал, то скрипт B его перезапускает. Скрипт B можно писать на питоне, а можно на другом языке.
#3 Фев. 2, 2021 23:44:11
Это правда так сложно перезагрузить программу в Python?
Renaldas
Неужели так сложно перезапустить программу, то, что в некоторых других оболочках можно
Причем тут питон. Ваша оболочка windows 10. Вот для него и гуглите как запустить процесс как службу.
#4 Фев. 3, 2021 12:00:16
Это правда так сложно перезагрузить программу в Python?
Renaldas
Я часа 3 провел гуугля как можно автоматически сделать перезапуск, но ума сделать что-то рабочее мне не получается.
Тут нужно понимать откуда вы хотите “автоматически сделать перезапуск”и как вы его запускаете?
вот такой примитивный скрипт запускает сам себя после завершения .
import sys import os import time python = sys.executable print(‘hello World!!’) time.sleep(5) print(‘work finished’) os.execl(python, python, * sys.argv)
другой вариант, вам уже предложил py.user.next создать скрипт который будет запускать, например, через subprocess(или както по другому, сейчакс это не имеет принципиальной роли) ваши скрипты, и контролировать, если процесс завершен запускать его еще раз.
[code python][/code]
Бериегите свое и чужое время.
Отредактировано PEHDOM (Фев. 3, 2021 12:03:37)
#5 Фев. 3, 2021 14:46:22
Это правда так сложно перезагрузить программу в Python?
Renaldas
Проблема та, что время от времени сайт, с которого я получаю данные либо виснет, либо дает какие-то неправильные данные, и программа останавливается и выходит
Я представлял это,как функция в которой рабочий скрипт обернутый в try ,except. Функция работает в возвращает код работоспособности, как у реквест, если ошибка,то далее алгоритм который через сколько то времени пробует запускать функцию.,и ещё смс уведомление или включение сирены гражданской обороны
#6 Фев. 3, 2021 21:30:32
Это правда так сложно перезагрузить программу в Python?
xam1816
Я представлял это,как функция в которой рабочий скрипт обернутый в try ,except.
Случаи бывают разные. Скрипт может сожрать всю допустимую для процесса память, Наоткрывать файловых дескрипторов сверх лимита. Те прийти в состояние когда данный процесс однозначно не может дальше жить. try except не спасет отца русской демократии.
Вот для этих случаев и есть службы. операционка позаботится чтобы процесс воскрес.
Бывают и более жесткие случаи, когда процессы циклятся или операционная система становится нестабильна, на это есть вотчдог таймеры…
Отредактировано doza_and (Фев. 3, 2021 21:31:44)
#7 Фев. 3, 2021 22:06:05
Это правда так сложно перезагрузить программу в Python?
PEHDOM
другой вариант, вам уже предложил py.user.next создать скрипт который будет запускать
Это монитор. Шаблон такой архитектурный. В Erlang’е есть такие, благодаря чему он отказоустойчивый и широко используется в телекоме, где кучи всяких устройств с аппаратными ошибками, нестабильным электричеством и прочим.
В Erlang’е изначально много легковесных параллельных процессов можно запускать и они независимы — действуют сами по себе, поэтому там есть средства для работы с ними и всё устроено удобно в этом плане. Вот такой процесс может грохнуться в результате чего-нибудь — свет отрубили, например. И чтобы ничего не менять в нём, так как он исправен и там просто с аппаратурой что-то, придумали вот эти процессы-мониторы, которые следят за обычными процессами и перезапускают их по новой, если те падают. Так там надёжность обеспечивается. И эта модель отлажена уже десятилетиями.
Отредактировано py.user.next (Фев. 3, 2021 22:09:31)
#8 Фев. 4, 2021 22:57:39
Это правда так сложно перезагрузить программу в Python?
py.user.next
Тебе надо написать второй скрипт B, который запускает первый скрипт A и следит за ним. Если скрипт A выпал, то скрипт B его перезапускает. Скрипт B можно писать на питоне, а можно на другом языке.
Да, я этот вариант понял и провел какой час спрашивая у гуугла, как это сделать, но пока что моих знаний не хватило. Я пробовал определить PID первого процесса и во втором скрипте задать проверку, есть ли такой процесс, но “завалил” дело на банальном — не смог понять, как другому скрипту передать величину переменной (PID) из первого.
#9 Фев. 5, 2021 09:15:30
Это правда так сложно перезагрузить программу в Python?
Renaldas
но “завалил” дело на банальном — не смог понять, как другому скрипту передать величину переменной (PID) из первого.
Обычно первый процесс(котороый нужно мониторить), в заранее определенном месте, создает файл, в который при запуске помещает свой pid. При штатном завершении он этот файл удаляет/очищает. Второй процесс смотрит если файла нет или он пустой, значит процесс не запускали или штатно остановили, если там есть pid то смотрит в процессах, и если не находит процесса с таким pid то значит процесс завершился аварийно, и нужно его перезапустить.
[code python][/code]
Бериегите свое и чужое время.
#10 Фев. 5, 2021 11:24:58
Это правда так сложно перезагрузить программу в Python?
вот так баловался с блокнотом,выключал его,он через 5 сек запускался
import subprocess import time notepad = subprocess.Popen(‘C:\Windows\System32\notepad.exe’) while True: if notepad.poll() != None: time.sleep(5) print(‘перезапуск’) notepad = subprocess.Popen(‘C:\Windows\System32\notepad.exe’)
не знаю на сколько он эффективен,не вникал
А так наверное на винде процесс можно запустить через службу,которая при падении будет его перезапускать
Отредактировано xam1816 (Фев. 5, 2021 11:40:10)
Источник: python.su