How do I handle Windows Terminal Closing event in Python? - python

I run a .py script with Windows Terminal using 'py' command. Is there any callback function that I can add to that .py script to handle the event of closing the Terminal Windows unexpectedly? (hit the 'X' button for example)

You can try like this:
import time
def on_exit(sig, func=None):
print("exit handler")
time.sleep(10) # so you can see the message before program exits
-Windows:
if you install pywin32 package, you can :
import win32api
win32api.SetConsoleCtrlHandler(on_exit, True)
If you are on Windows, opt for win32api.
-Un*x:
Or, using python internal "signal" library, if you are using under *nix system:
import signal
signal.signal(signal.SIGTERM, on_exit)

Related

Python code to close all open application in windows

I am working on pyautogui for locateonscreen but I need to make sure I have a clean windows prior to running it.
I need help with a code that will kill/close all open/active windows application and then open a single exe using subprocess.
you can use the psutil library to close all open/active windows applications and then open a single exe using the subprocess module:
import psutil
import subprocess
# Kill all open/active processes
for proc in psutil.process_iter():
proc.kill()
# Open a single exe using subprocess
subprocess.Popen("C:\\path\\to\\exe.exe")
Note that the psutil.process_iter() returns a list of all running processes on the system, and proc.kill() method is used to kill each process. The subprocess.Popen method is used to open the exe file. Make sure that you provide the correct path to the exe file. Please be aware that this script will close all open applications, including any unsaved work in progress.
You should use it with caution, or for testing purpose only.
you can instead reduce all open windows. this is safer!
import win32gui
import win32con
import subprocess
def minimize_all():
def callback(hwnd, hwnds):
if win32gui.IsWindowVisible(hwnd) and win32gui.IsWindowEnabled(hwnd):
hwnds.append(hwnd)
return True
hwnds = []
win32gui.EnumWindows(callback, hwnds)
for h in hwnds:
win32gui.ShowWindow(h, win32con.SW_MINIMIZE)
minimize_all()
# Open a single exe using subprocess
subprocess.Popen("C:\\path\\to\\exe.exe")
This script uses the win32gui library to enumerate all open windows, and the win32con library to minimize them.
why not minimize all windows with shortcut WIN + D ?
import pyautogui
pyautogui.hotkey('winleft','d')

Is it possible to write to Command Prompt with python?

Im opening Command Prompt with
os.startfile('C:\\WINDOWS\\system32\\cmd.exe')
and after opening the program id like to write the python file for it to run
C:\Users\user\Documents\Python>examplefile.py
when python opens the command prompt it starts with
C:\Users\user\Documents\Python>
so I would just need to add on the file to the end of the line and run it, is this possible?
You can use the os module to open cmd and the keyboard module for writing in cmd
import os
import keyboard
import time
os.system("start cmd")
# Because we don't want the `keyboard` module to write before cmd gets opened.
time.sleep(0.1)
keyboard.write("Anything you want")
I would suggest you to use os.startfile (this link is for 2.7 documentation)
Otherwise importing keyboard and using keyboard.write("python3 myfile.py") should work.

Working on an auto clicker with python and I can't open the file

Every time I open the file through file explorer it immediately closes. I'm working on it through VS code and it runs fine through there but when I double click the file (.py) it opens the closes. I've tried making it into an exe (to give to my friend) through pyinstaller and without a -w it still closes and with a -w it says "Fatal error detected, Failed to execute script AutoClicker". I tried -w to see if the program would stay open but I assume that it closes because there is nothing to show.
import mouse
import keyboard
while True:
if keyboard.is_pressed(','):
mouse.click('left')
if keyboard.is_pressed('.'):
break
You should try structuring your loop like this:
while True:
if keyboard.is_pressed(','):
mouse.click('left')
elif keyboard.is_pressed('.'):
break
elif ...
And run your code from the terminal, if you are on Windows press Win+R, type cmd and go to the directory where your file resides (cd <directory name>). Then you can open the file with Python by typing python <filename>. If you see any errors, you should probably pip install the keyboard and mouse packages you are trying to import.
Try using the pyautogui (and keyboard) module, as shown below:
from keyboard import is_pressed as isp
from pyautogui import click
from time import sleep
def clicky(click_key='.', stop_key='F10'):
while not isp(stop_key): # Execute till the stop key is pressed
if isp(click_key): # If click key is pressed,
# Click the left button two times with a 0.2 second delay between clicks
click(button='left', clicks=2, interval=0.2)
sleep(0.5) # Wait .5 seconds before checking again
clicky() # Run the function
The above code works perfectly on my Windows PC. If it does not work for you, try using the pydirectinput module, it's an updated version of pyautogui (With almost the same functions - check the link). Quoting from the PyPI page:
PyAutoGUI uses Virtual Key Codes (VKs) and the deprecated mouse_event() and keybd_event() win32 functions. You may find that PyAutoGUI does not work in some applications, particularly in video games and other software that rely on DirectX. If you find yourself in that situation, give this library a try!

How can I send a keyboard interrupt ctrl+] to the terminal using a Python program?

I'm currently working on a ESP32 project in which there is a command named 'idf.py monitor'. This command outputs strings into the bash only after the keyboard interruption 'ctrl+]'.
It's annoying to finish the program by tabbing 'ctrl+]' everytime. So that I wrote a python script to execute the command automatically.
import os
command='idf.py monitor'
r=os.popen(command) #execute the command
context=r.readlines() # get the command output
print(context)
However, the 'print' function only works after the key interrupt 'ctrl+]'.
So my question is: How can I write a python script that can send the keyinterrupt 'ctrl+]' to my shell automatically?
(I tried using process.kill() or process.terminate() which send 'ctrl+c', but that doesn't work)
You can use a module named as keyboard
pip install keyboard
import keyboard
keyboard.press_and_release('ctrl+]')

Lock windows workstation using Python

Is there a way to lock the PC from a Python script on Windows?
I do not want to implement some kind of locking on my own - I'd like to use the same lock screen that's also used when the user presses WIN+L or locks the machine via the start menu.
This can be done with the LockWorkStation() function from user32.dll:
This function has the same result as pressing Ctrl+Alt+Del and clicking Lock Workstation.
In Python it can be called using using the ctypes/windll FFI from the Python stdlib:
import ctypes
ctypes.windll.user32.LockWorkStation()
A good solution that makes us avoid using Libraries/DLL files is to use the command prompet/ power shell.
try running this command in your cmd rundll32.exe user32.dll, LockWorkStation....The PC is Locked!!
so we can use subprocess to run this command like this:
import subprocess
cmd='rundll32.exe user32.dll, LockWorkStation'
subprocess.call(cmd)
One more solution :
Run command to install the necessary package
pip install pyautogui
Run the below code
import pyautogui
from time import sleep
pyautogui.hotkey('win', 'r')
pyautogui.typewrite("cmd\n")
sleep(0.500)
pyautogui.typewrite("rundll32.exe user32.dll, LockWorkStation\n")

Categories

Resources