Как сделать перезапуск программы питон

Я захотел сделать простенькую игру на 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( ‘Вы не угадали(( Может попробуем снова ? (да, нет) :’ )

Автозапуск программ на python

Restart Script in Python

Restart Script in 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

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.

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.

Самый БЫСТРЫЙ стандартный цикл Python − Интеграция с языком Си

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.

Читайте также:
Данный объект был создан в следующей программе acrobat

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 python-script from within itself

I have a python-based GTK application that loads several modules. It is run from the (linux) terminal like so:

./myscript.py —some-flag setting

From within the program the user can download (using Git) newer versions. If such exists/are downloaded, a button appear that I wish would restart the program with newly compiled contents (including dependencies/imports). Preferably it would also restart it using the contents of sys.argv to keep all the flags as they were.

So what I fail to find/need is a nice restart procedure that kills the current instance of the program and starts a new using the same arguments.

Preferably the solution should work for Windows and Mac as well but it is not essential.

17 Answers 17

You’re looking for os.exec*() family of commands.

To restart your current program with exact the same command line arguments as it was originally run, you could use the following:

I think this is a more elaborate answer, as sometimes you may end up with too many open file objects and descriptors, that can cause memory issues or concurrent connections to a network device.

I know this solution isn’t technically what you are asking for but if you want to be 100% sure you freed everything or don’t want to rely on dependencies you could just run the script in from a loop in another:

Then you can restart main.py as simply as:

UPDATE — of the above answer with some example for future reference

And i have server.py where i need to restart the application itself, so i had:

but that did not restart the application itself by following runme.sh, so when i used this way:

Then i was able to restart itself

For me this part worked like a charm:

Works at Windows (Without args)

Try this work with Windows:

when you want to restart the script call this function

I have just a little amelioration on the code of #s3niOr.

In my case there are spaces in the path of the python file. So by adding a proper formatting, the problem can be solved.

Notice that in my case my python file has no other arguments. So if you do have other arguments, you have to deal with them.

This solves the problem of restarting a python script that has spaces in its path :

I was looking for a solution to this and found nothing that works on any of the stack overflow posts. Maybe some of the answers are too out of date, e.g. os.system has been replaced by subprocess. I am on linux lubuntu 17.10, using python 3.

Two methods worked for me. Both open a new shell window and run the main.py script in it and then close the old one.

1. Using main.py with an .sh script.

I use lxterminal but you could probably use any.

In the file called restart.sh (chmod +x to make it executable)

Then in the main.py use this when you need to call it

2. From within main.py

you can open with webbrowser.open then exit the script

Add this to your main.py

I’m using this to give an option for the users to restart the script within the console. Hope it could be a help.

So the user can input an option ‘Y/N’ to restart the program or not.

The old answers utilize exec which is fine, but not scalable in the long run. There’s also an approach of master/slave process relationship or a daemon/service in the background which will watch for the changes but is mostly OS specific or even different between the same family of OSs (init.d vs systemd vs whatever).

There’s also a middle ground by using a bootstraping technique and a simple subprocess.Popen() call thus assuming that the user who started the original program had the permissions to run the executable (such as /usr/bin/python ) should also work without any permission errors due to utilizing the exactly same executable. Bootstraping because it’s the main program that’s creating and calling the restarter a.k.a. pulling itself by own bootstraps after the initial start.

So a simple program (re)starter can be written like this, as written in the other answers:

Читайте также:
Самая точная программа для измерения температуры

Depending on your needs you might want to do some cleanup afterwards such as removing the (re)starter file.

This file would be called from your main program. However, your main program may have an exception, utilize sys.exit() , may be killed by a OS signal and so on. Python provides multiple hooks how to do something after such an event seamlessly, one of which is implemented by the atexit module. atexit doesn’t care about Python exceptions and about some signals either ( SIGINT ) (for further improvement check signal module), so it’s a reasonable choice before implementing own signal handler(s).

This allows you to register a function that will execute once your program stops. That function can be anything in Python, so it can write a file too.

Похожие публикации:

  1. Как в зуп настроить районный коэффициент
  2. Как объединить два абзаца в один в word
  3. Как убрать рекламу в relax плеере
  4. Почему во время игры выключается монитор а системник работает

Источник: gshimki.ru

Restart Script in Python

Restart Script in 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.

Разделение близнец.

Please enable JavaScript

Restart the Program Script in Python Using the os.execv() Function

The os.execv(path, args) function executes the new program by replacing the process. It does not flush the buffers, file objects, and descriptors, so the user needs to separately buffer them before calling the os.execv() function. The os.execv() function does not require the path parameter to locate the executable program.

Therefore, to restart a program using the os.execv() function, we first need to flush the buffers and file descriptors using the sys.stdout.flush() and file.flush() methods and then call the os.execv() method. See the below example code.

import os import sys sys.stdout.flush() os.execv(sys.argv[0], sys.

argv)

Источник: www.delftstack.com

Как перезапустить мою программу нажатием кнопки «r»?

Хорошо, я создал Space Invaders в Python 3.7.4 и Pygame 1.9.6. У меня все работает, ошибок нет или чего-то подобного. У меня даже есть кнопка паузы, чтобы отлично работать. Это просто, когда на экране появляется текст «ИГРА ЗАВЕРШЕНА», означающий, что вы проиграли. Я хотел бы открыть окно, чтобы снова попросить воспроизвести после того, как текст исчезнет. Но я просто не знаю, с чего начать.

Я просмотрел Как перезапустить программу на основе при вводе пользователем? за помощью, но я не мог понять, где это реализовать или где посмотреть. Это был мой первый настоящий проект / игра, созданная в Pygame. Код:

paused = False running = True while running: # RGB = Red, Green, Blue screen.fill((0, 0, 0)) # Background Image screen.blit(background, (0, 0)) for event in pygame.event.get(): if event.type == pygame.QUIT: running = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_p: # Pausing paused = True if event.key == pygame.K_u: # Unpausing paused = False if not paused: »’The rest of the code, with the movement key presses, etc.»’

Поскольку все, что находится выше цикла «во время выполнения», постоянно загружается или для извлечения данных, таких как изображения, координаты того места, где должны быть изображения, фоновая музыка и т. Д. Поэтому я хотел, чтобы это было похоже на приостановку / снятие паузы в коде. когда я нажимаю, скажи «р». Я хочу воспроизвести программу, не выходя из нее. Так что буду очень благодарен людям за помощь. Спасибо вам всем.

person Axhul schedule 08.09.2020 source источник

Попробуйте поместить свой цикл while / переменные, которые необходимо сбросить, в функцию. Чтобы запустить игру в первый раз, вы вызываете эту функцию, а затем, чтобы перезапустить ее, вы можете просто вызвать ее снова. — person Starbuck5 nbsp schedule 09.09.2020

Но разве это не будет вызвано только один раз, когда я перезапущу его, а что, если я захочу сделать это снова. — person Axhul nbsp schedule 09.09.2020

Но как только появляется текст GAME OVER, он прерывает цикл while. — person Axhul nbsp schedule 09.09.2020

Ответы (1)

Вы должны создать функцию или методы в объекте для сброса данных и использовать их перед каждой игрой. Для этого можно использовать внешний while -loop.

# executed only once pygame.init() screen = . # .. load data . player = . enemy = . gameing = True while gameing: # reset data before every game player.reset() enemy.reset() score = 0 paused = False running = True while running: for event in pygame.event.get(): if event.type == pygame.QUIT: # exit game running = False gameing = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: # restart game (but don’t exit) running = False #gameing = True if event.key == pygame.K_x: # exit game and program running = False gameing = False if game_over: # restart game (but don’t exit) running = False #gameing = True
def reset(): global score, paused, running player.reset() enemy.reset() score = 0 paused = False running = True # executed only once pygame.init() screen = . # .. load data . player = . enemy = . # (re)set data before first game reset() while running: for event in pygame.event.get(): if event.type == pygame.QUIT: # exit game running = False gameing = False if event.type == pygame.KEYDOWN: if event.key == pygame.K_r: # restart game (but don’t exit) #running = False # DON’T DO THIS reset() if event.key == pygame.K_x: # exit game and program running = False if game_over: # restart game (but don’t exit) #running = False # DON’T DO THIS reset()

Для этого нужно использовать global для каждой переменной, которую вам нужно сбросить, чтобы это было более полезно, когда у вас есть код в классах, и вы можете использовать self. вместо global

person furas schedule 08.09.2020

Вы показываете мне, что это помогает мне понять это намного лучше, большое вам спасибо. Я не собираюсь просто копировать и вставлять или что-то еще, чему я научусь из этого. — person Axhul; 09.09.2020

Источник: questu.ru

Рейтинг
( Пока оценок нет )
Загрузка ...
EFT-Soft.ru