Stopping a python program - python

I have a python program that displays battery voltages and temperatures in an electric car. I typically run it from a command line on a Mac by simply using the up arrow to find the command to change directory, and then up arrow to find the command to run the program. We figured out how to write a script that does this automatically and saved it as an application. It works great but don't know how to exit the program. I use control C when using the command line. How do I accomplish in in a script or app? I prefer not to ask our customers to use the command line.

import sys; sys.exit()
will stop the Python program. When you call that code is up to you and depends on the details of your program (you could have it happen when a certain button is pressed, or after a certain amount of time, or when other conditions are met). Also be careful if you have to do any "clean-up" before the program ends- this also depends on the type of application.
If for some reason you want to stop it in exactly the same way as hitting Control-C, you could do
raise KeyboardInterrupt

Related

Python3 -- Function similar to win32api.SetConsoleCtrlHandler() that works in PowerShell

Win32API commands seem not to work with PowerShell (I'm running 7, but I assume unimportant), only with the inferior IMHO Command Prompt.
I am building a program (a glorified HOSTS site blocker) that runs on the simple structure of "query command, execute command; repeat until user prompts to exit" and one of the things the user can query the program with is UNBLOCK category>site_nickname FOR minutes. This runs the program in one thread, starts a timer in another thread so the user can keep using the program as they desire. After the timer, the UNBLOCK command the program ran at start is undone so the user can get back to work. What I want to avoid is the user being able to cheat fate by saying UNBLOCK, then closing the program via the 'close' button, terminating the PowerShell instance, my Python program, and all its threads and thus ensuring the UNBLOCK command is never undone with a partner BLOCK command.
The user can exit the program by typing EXIT or CANCEL. This has the program wrap up, and then run sys.exit(). As I discovered, using the atexit library just basically does that but runs the function you want afterwards, does not intercept a close-button click. And setting the console control handler only seems to work in Command Prompt (whose support for ANSI escapes/emojis/Unicode probably too, seems to be spotty), also, the window_exit() function, or I guess the proper term is "method" --
def window_exit(signal_type):
sure = ask_input("Wait, wait! Are you sure you want to exit?") # input plus ANSI escape sequence, highlights the input prompt in blue and adds ">>" on a new line
if sure == "Yes":
evaluate("EXIT") # runs this command as if the user typed it in to be evaluated by my program
-- does not accept input properly. Instead, it displays the message and then for some reason decides I am trying to pull some "Press any key to continue ..."-type stuff, when I want the user to be able to type whatever and then have it be evaluated.
What can I do so any attempt to "cheat" and exit the program early is acknowledged and dealt with?

Closing a python file inside another python file

I have made a code to open an inputed python file on key command in python pygame_functions
import os, pygame_functions
if spriteclicked(Sprite1):
os.system('file.py')
Similarly how do I close an inputed python file on key command
Your question is not very clear. By 'inputed file' do you mean that the name of the file is from user input? Or that the data in the file is from user input in some way and you want to access it?
I'm going to skip past that part and try to address what I think you are asking about. The line:
os.system('file.py')
tells the OS to run the script file.py. Because you are running it with os.system() your control is limited after you do that. You run the program and do not regain control until that program exits.
If you want to be able to run the command and then stop it when the user types a key, you need to run it in a different way. You would have to run it in a subprocess or a different thread so that you still have an active thread that is not blocked. It can monitor for the user input and then have it do something to shut it down. Exactly how you would shut it down would depend to some degree on the command you ran and how you started it.
Try looking here for some guidance on replacing the os.sytem() call.

How to catch a process in python?

I'm currently making a lil' launcher for PortableMu while in an internship.
We (company and I) modeled a special mode for the Mu-Editor and we are shipping it with PortableMu so that users don't need to install Mu and/or Python to use it.
The problem of PortableMu for Windows is, that you start it with a .bat and this doesnt give you any feedback.
You click, you wait ~1-2min and maybe Mu-Editor will popup.
This is not very userfriendly.
So my duty is to create a launcher.
My launcher is a simple thing: Only lil "welcome" a picture and a button to start PortableMu. It works on my private windows10.
Now I want to add in randomly picked messages for simulating "loading" which shall stop when the Mu-Editor pops up. Simply to bridge the time
Is there a method to catch when this happens?
Alas:
Can Python catch the moment when Windows opens the task/process for Mu-Editor?
If, how?
use the tasklist
subprocess.Popen('tasklist').comunicate()[0] will return all the tasks currently happening in windows, simply do this every minute or so and check for your task. There are ways to make this pass without a command window popping up, here's one that i use often
command =subprocess.Popen(["ping","-n","1","-w","100", str(ip)], stdout=subprocess.PIPE, shell=False, creationflags = 0x08000000)
reply = str(command.communicate()[0])

If I Keyboard Interupt a running Python script, is there a way to begin again where it left off? (windows)

I have a long-running script at work (windows unfortunately) where I programmed it to print the current analysis results if I ctrl-c. However, I was curious if after doing ctrl-c, I could start the script running again where it left off?
This is actually 3 questions:
-is it possible to do this without any programming changes? - e.g. I accidentally hit ctrl-c and want to retroactively start it where it left off
-can I use a command like ctrl-z (only on Mac I believe) on windows and program the script to print results when I issue it?
-what is the best programmatic way of automatically finishing the execution of the line I am on (massive .txt file of data) when I use an interrupt command, store that line number (in a file maybe), and restart the program on the next line with the next execution?
Thanks!
(FYI: I'm a novice Pythoner and my script currently takes about 10 min to perform 1 million lines. Files I will use in the future will often have 100+ million lines)
The short answer to your first question is No. Ctrl-C signals the interpreter, which unwinds the stack, presents you with a stack trace, and halts. You can't recover from ctrl-C for the same reason that you can't recover from any other untrapped exception. What you are asking for is a quick way to put Humpty Dumpty back together again.
You can restart a chess game from any point simply by laying out the pieces according to a picture you made before abandoning the game. But you can't easily do that with a program. The problem is that knowing the line number where the program stopped is not nearly enough information to recreate the state of the program at the time: the values of all the variables, the state of the stack, how much of the input it had read, and so forth. In other words, the picture is complicated, and laying out the pieces accurately is hard.
If your program is writing to the Windows console, you can suspend output by pressing ctrl-S and restart it by pressing ctrl-Q. These control characters are holdovers from the days of Teletype machines, but modern terminal emulators still obey them. This is a quick way to do what you want without program changes. Unsophisticated, but maybe good enough to begin with.
And your program will probably run a lot faster if it writes its output to file, for later examination in a text editor, rather than writing directly to the Windows console.
A full-on solution to your problem is something that I hesitate to recommend to a novice. The idea is to split calculation and display into two processes. The calculation process does its thing and feeds its results line by line to the display process. The display process listens to the calculation process and puts the results that it gets on the screen, but can also accept pause and resume commands. What happens while it is in the paused state is a design decision. You can decide either that the calculation process should block (easier option) or that it should buffer its results until the display process is ready to accept them again (harder option).

my Python program shut down when i executing by double click

i write some python program.
i usually execute my program by CMD
but this time, i tried to execute program by double click
it works well until interpreter meet input code.
when i input some texts, it shut down
my input code is
for i in (input('range input => ')).split(' '):
range_list.append(int(i));
it works totally well when i execute by path(py ~.py) through the CMD
can you help me?
The interpreter is running in an endless loop. Executing your program from windows or via the command line using python will run and exit the program immediately.
At the end of your program just add
input()
This will keep it open so you can see your results.
Yeah when the program is done, it closes.
You can add something like x = input() at the end if you want to keep it open, or just run it in cmd.
Your program opens in a windowed mode when you double click it. The window will disappear / close down when the program finishes, which happens a lot fast after you have entered all the required inputs.
If you wish to see the output before the program exit, expect an input at the end of your program.

Categories