Reputation: 341
I have a python program that will never exit automatically. However, it does need to do so at some point. It must run without the console, so I saved it as a .pyw, but this means there is no X to click on to close it. How do I close this manually without restarting the machine? I am on Windows, in case it needs the command line.
Upvotes: 4
Views: 4089
Reputation: 1
you can include threading in your script to take input
from pynput.keyboard import Key, Listener
import threading
import sys
def on_press(key):
global pause
if str(format(key))[1]=='`':
sys.exit()
def fun():
YOUR CODE HERE
threading.Thread(target=fun).start()
with Listener(
on_press=on_press) as listener:
listener.join()
this will exit your code when pressed "`" sys.exit() will stop main thead but you need to manage in way that fun() thread also ends to end the program actually
Upvotes: 0
Reputation: 388
You can make a file. The .pyw program should check it about every 1 seconds. If the file changes, run the quit()
command in the .pyw program. But don't check it every tick, as it will fail because the file is in a 'changing' state.
Example:
### Do Something here...
from datetime import datetime
last = 0 #Record the last time to do checking, for now, just put it to any number you want
while True:
now = datetime.now()
second = now.second
if now != second:
### Do checking here for example, a file called "quit_state.txt"
date = open("quit_state.txt",'r').read().strip() ### Strip the data
if date == "quit":
quit()
Just Change the file data to quit
and the program will stop
Upvotes: 0
Reputation:
You could just do taskkill /IM pythonw.exe /F if you have only one pythonw running. Type this into a terminal or create a link on the desktop or wherever you want.
Upvotes: 4