killing python application after exiting it - python

I’m starting finishing off my new simple app and because Python isn’t my main programming language I’m struggling a lot. I would like to add a function which would kill everything - every service in the app, after clicking an exit button. (So maybe with a global variable?)
I want to do it as simple as possible. I was wondering if there is anything similar to isServerOn or so.
What I have so far is just this code below and if there would be a chance to add just one or few lines then it would be the best. Thank you all so much!!
import sys
def quit()
sys.exit()

To stop a python script use the keyboard: Ctrl + C
To stop it using code you can use these sections (Python 3) :
raise SystemExit
you can also use:
import sys
sys.exit()
or:
exit()
or:
import os
os._exit(0)

Related

How to terminate/killall a program in python

The first simple answer to the Linux equivalent killall(ProgramName)
The program is to be a toggle program. I can launch Firefox/program.
def tolaunch(program):
os.system("firefox")
When launched I wish to save the name of program launched, in array(simple to do), then launch the program(Firefox)/program.
Here the idea off the toggle come’s in, when Launched and I have finished my browsing, I wish to call the same program(mine), check the array for said program and exit Firefox/program, by running a simple command like killall(“Firefox”) but in Python code. I don’t want to write a long winded command/script, that first has to workout the ‘pid’.
I seem very close to the answer but cant find it.
Edit: people asked for code example | here is my code
# Toggler for macro key -|- many keys = one toggler program
import os
import sys
def startp(program):
# hard-coded
os.system("firefox")
def exitp(program):
# os.close(program)
sys.exit(program)
# Begin
# hard-coded : program start
startp("Firefox")
# loop while program/s active
# exitp("Firefox")
# exit(program) or program end
I tried to include some explanations in way off comments
What you are looking for is the sys.exit() command.
There are 4 functions that exit a program. These are the quit(), exit(), sys.exit() and os._exit(). They have almost same functionality thanks to the fact that they raise the SystemExit exception by which the Python interpreter exits and no stack traceback is printed on the screen.
Among the above four exit functions, sys.exit() is mostly preferred because the exit() and quit() functions cannot be used in production code while os._exit() is for special cases only when an immediate exit is required.
To demonstrate this behavior using the sys.exit() function:
import sys
i=0
while i in range(10):
i += 1
print(i)
if i == 5:
print('I will now exit')
sys.exit()
elif i > 5:
print('I will not run, program alredy exited :(')

I created a python bind for CS:GO with pyautogui but it doesnt work

I created a simple bind script. It works on IDLE Python but it doesn't work in CS:GO. Do you know why?
Mayby it must be on background to work?
import keyboard
import pyautogui
import time
def EventListen():
while True:
try:
if keyboard.is_pressed('n'):
pyautogui.press('`')
pyautogui.typewrite('say EZ')
pyautogui.press('enter')
pyautogui.press('`')
EventListen()
except:
EventListen()
EventListen()
I don't see the need to use pyautogui since you are already using keyboard which is sufficient to perform the tasks you need. I have made some changes to your code
import time
import keyboard
def EventListen():
while True:
try:
if keyboard.is_pressed('n'):
keyboard.press('`')
keyboard.write('say EZ')
keyboard.press('enter')
keyboard.press('`')
elif keyboard.is_pressed('/'): #add something to end the process
break
except:
EventListen()
time.sleep(0.001)
EventListen()
There is no need to call the function in the while loop, as it will anyway be executed infinitely unless you kill the process. I don't see why the script wouldn't run in the background, in fact I am typing this
n`say EZ
`
using the script. What might be possible is that your previous program ran continuously, causing high CPU usage which might have competed with the game's demand. I recomend you to add a small delay before every iteration of the while loop, in this case I have added 1 ms delay, which will cause significant reduction in CPU usage. I am not sure if that solved your problem as I am unable to reproduce your exact case, let me know if it helped.
EDIT : I forgot to mention, I have added another binding of keyboard.is_pressed('/') which will make the program break out of the loop and hence terminate it when / key is pressed. You can change this as you like. If you don't want any other binding as such (which I don't recommend) then you can rely on manually killing the task.
you should make an exe with pyinstaller and you run it background

Hide cursor when a specific program is running

I'm checking if the game is active and If it is I'm trying to hide the mouse cursor just for comfort reasons since it annoys me. But I can't find any way to do it... Any suggestions? I'm pretty new to Python.
import psutil
def isRunning(name):
for pid in psutil.pids():
prcs = psutil.Process(pid)
if name in prcs.name():
return True
while(isRunning("Brawlhalla")):
# do stuff here
You could do this using an external program. If you are under Linux, check unclutter (https://packages.ubuntu.com/bionic/x11/unclutter for example - if you are using ubuntu).
This answer lists other ways to hide the mouse cursor more or less permanently.
By the way this is not strictly speaking a Python question, and using a python script is probably not the proper way to achieve what you want... You'd better launch unclutter or one of its friends from a console and be done with it.
But assuming you really insist on using Python and your isRunning() code is correct, one naive way to implement what you want in python could look like this (leaving aside corner cases handling):
from time import sleep
import subprocess
(your isRunning code here)
proc = subprocess.Popen(["unclutter", "-root", "-idle", "0"])
while (isRunning("Brawlhalla")):
sleep(1)
proc.terminate()

How use Python to simulate keybaord click to control game?

I'm trying to create a python script to automate a game.
I already tried these libs:
pyautogui
pywin32
ctypes (I imported this code and calling the function PressKey, https://github.com/Sentdex/pygta5/blob/master/directkeys.py)
My code is like this:
from directkeys import PressKey, ReleaseKey, W
import time
print("Script is gonna start in 5 seconds")
time.sleep(5)
PressKey(W)
time.sleep(10)
ReleaseKey(W)
print("Script finished")
I tested this script at notepad, it's working pretty well, but it's not working in the game at all.
I thought it was because of need to be direct input, but I think ctypes is already sending input as direct input.
How can I automate the game using python?
I'm going to elevate my comment to an answer since I believe it's what you're looking for.
The W is not the proper input for the PressKey and ReleaseKey functions. They're looking for hex code input. You can find the proper hex codes here: https://learn.microsoft.com/en-us/windows/desktop/inputdev/virtual-key-codes
The W hex code particularly is 0x57. So replace "W" with "0x57":
from directkeys import PressKey, ReleaseKey, W
import time
print("Script is gonna start in 5 seconds")
time.sleep(5)
PressKey(0x57)
time.sleep(10)
ReleaseKey(0x57)
print("Script finished")
What I did was to make sure it was running either the script or the IDE in Administrator mode.
For some reason, games I wrote scripts for like Black Desert Online or CSGO only detect key presses when I am running it in Administrator.

Python: How to quit CLI when stuck in blocking raw_input?

I have a GUI program which should also be controllable via CLI (for monitoring). The CLI is implemented in a while loop using raw_input.
If I quit the program via a GUI close button, it hangs in raw_input and does not quit until it gets an input.
How can I immediately abort raw_input without entering an input?
I run it on WinXP but I want it to be platform independent, it should also work within Eclipse since it is a developer tool. Python version is 2.6.
I searched stackoverflow for hours and I know there are many answers to that topic, but is there really no platform independent solution to have a non-blocking CLI reader?
If not, what would be the best way to overcome this problem?
Thanks
That's not maybe the best solution but you could use the thread module which has a function thread.interrupt_main(). So can run two thread : one with your raw_input method and one which can give the interruption signal. The upper level thread raise a KeyboardInterrupt exception.
import thread
import time
def main():
try:
m = thread.start_new_thread(killable_input, tuple())
while 1:
time.sleep(0.1)
except KeyboardInterrupt:
print "exception"
def killable_input():
w = thread.start_new_thread(normal_input, tuple())
i = thread.start_new_thread(wait_sometime, tuple())
def normal_input():
s = raw_input("input:")
def wait_sometime():
time.sleep(4) # or any other condition to kill the thread
print "too slow, killing imput"
thread.interrupt_main()
if __name__ == '__main__':
main()
Depending on what GUI toolkit you're using, find a way to hook up an event listener to the close window action and make it call win32api.TerminateProcess(-1, 0).
For reference, on Linux calling sys.exit() works.

Categories