Why my app keep opening when I use shortcut in Python? - python

I tried to create a program to open a app with a specific shortcut but when I press my keys it keep opening and didn't stop until I stopped the program
import keyboard
import time
import subprocess
while True:
if keyboard.is_pressed('ctrl+space+b'):
subprocess.Popen([r"C:\\Program Files\\Everything\\Everything.exe"])
time.sleep(1.5)

How about try this code
import keyboard
import subprocess
import threading
def run_my_program():
subprocess.run([r"C:\Program Files\Everything\Everything.exe"])
while True:
if keyboard.is_pressed('ctrl+space+b'):
threading.Thread(target=run_my_program).start() # launch up the subprocess in parallel so input is not delayed
while keyboard.is_pressed('ctrl+space+b'):
pass # Wait until user lifts his hands off the keyboard

Related

How do you press a specific key to do something in python?

I want to know to press a specific key to do something in python and no, not the keyboard library it requires root permissions. I could just do sudo /bin/python3.7 "path of python file" but that's gonna be a pain. by the way here's my python code:
import keyboard
import pyautogui as auto
import time
auto.hotkey('alt', 'F2')
auto.write('mousepad')
time.sleep(int(1))
auto.write('do you want to start game?')
keyboard.wait('y')
from pynput.keyboard import *
import pyautogui as auto
import time
auto.hotkey('alt', 'F2')
time.sleep(int(1))
auto.write('mousepad')
time.sleep(int(1))
auto.write('do you want to start game?')
if key == Key.y:
# Stop listener
return False
def on_press(key):
doing_something_here()
with Listener(
on_press=on_press,
on_release=None) as listener:
listener.join()

While Loop No Longer Updating Data when added "Press Enter to Exit"

I am a beginner to Python and recently was making a **Discord Rich Prescense** application. The problem is that I was using a While Loop and added a "*Press Enter to Exit*" feature. This made the Rich Prescense stuck on One Quote. I have attached a screenshot of the problem.
from config import credentials
from data import quotes
from pypresence import Presence
import random
import time
def quotegen():
RPC = Presence(credentials.clientid)
RPC.connect()
while True:
RPC.update(details="Random Quote:", state=random.choice(quotes.quotes))
i = input("Press Enter to Exit")
time.sleep(30)
if not i:
break
Screenshot of what its supposed to do:
Using the keyboard module (https://pypi.org/project/keyboard/)
you can do it all.
I modified your code to fit your requirements:
import keyboard # using module keyboard
from config import credentials
from data import quotes
from pypresence import Presence
import random
import time
def quotegen():
RPC = Presence(credentials.clientid)
RPC.connect()
while True:
RPC.update(details="Random Quote:", state=random.choice(quotes.quotes))
i = input("Press Enter to Exit")
time.sleep(30)
if keyboard.is_pressed('enter'): # if key 'enter' is pressed
break

Python SetThreadExecutionState: How do I prevent screen display from turning off?

I am on Windows. I want to run a Python Script that involves keyboard activity hence my PC mustn't lock screen or go to sleep. Instead of changing my PC Sleep Setting, I want to use Python code to keep my Screen Display On for the whole duration of my Python Script.
I modified the code here Prevent sleep mode python (Wakelock on python) but it doesn't work. My screen display still offs automatically. MY modified code as below:
class WindowsInhibitor:
'''Prevent OS sleep/hibernate in windows; code from:
https://github.com/h3llrais3r/Deluge-PreventSuspendPlus/blob/master/preventsuspendplus/core.py
API documentation:
https://msdn.microsoft.com/en-us/library/windows/desktop/aa373208(v=vs.85).aspx'''
ES_CONTINUOUS = 0x80000000
ES_SYSTEM_REQUIRED = 0x00000001
ES_DISPLAY_REQUIRED= 0x00000002
def __init__(self):
pass
def inhibit(self):
import ctypes
print("Preventing Windows from going to sleep")
ctypes.windll.kernel32.SetThreadExecutionState(
WindowsInhibitor.ES_CONTINUOUS | \
WindowsInhibitor.ES_DISPLAY_REQUIRED)
def uninhibit(self):
import ctypes
print("Allowing Windows to go to sleep")
ctypes.windll.kernel32.SetThreadExecutionState(
WindowsInhibitor.ES_CONTINUOUS)
import os
osSleep = None
# in Windows, prevent the OS from sleeping while we run
if os.name == 'nt':
osSleep = WindowsInhibitor()
osSleep.inhibit()

to invert a GPIO input

This is my Code to start my other Code where i defined my Laser to start.
But in this Code i want to have a Button which starts my other script if i put press it.
But what this code does is it activate my code continuous.
What can i change in it ?
#!/usr/bin/env python
import RPi.GPIO as GPIO
import time
import os
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BCM)
#GPIO.setmode(GPIO.BOARD)
GPIO.setup(15,GPIO.IN) #GPIO17
#input = GPIO.input(27)
#print ("input",input)
while True :
#inputValue = GPIO.input(11)
#print ("input01",inputValue)
#time.sleep(1)
erg= GPIO.wait_for_edge(15,GPIO.RISING, bouncetime=20)
print ("Input",2)
#if (GPIO.input(11) == GPIO.HIGH):
#if erg==15:
print ("Input",1)
time.sleep(3)
#inputValue = 1
os.system("python /home/pi/gpio.py")
When you run os.system('python /home/pi/gpio.py') you start new process and your main process get back to work on its while loop.
As I understood your idea was to wait until button is pressed and then go to some other state waiting for something new to happen.
You don't need to start new process just import module (doc). When button was clicked break loop and run code from the imported module.
Also you may find it interesting to replace wait_for_edge with event_detected method. More about it here.

Waiting for user input when controlling 3rd party application via python script

I am writing a script intended to be used by members of a project team. As part of the script, I am launching a 3rd party proprietary application run through Citrix. I am going to use the script mostly to send keys to this application, but the first step once it launches is for the user to log in.
Because I would like the user to log in while the script is running, rather than asking for user/pass from some kind of GUI input earlier, and because the time it takes Citrix to launch varies, I would like to include some kind of logic that detects when the user has logged in and then resume the script from there, rather than including an obnoxiously long implicit wait or risking the script timing out.
Is there a way to detect user keystrokes using win32com.client (or to detect a change in state of the application itself)? See below for the relevant code to launch the app:
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
shell.Run('C:\Citrix\[rest of path])
EDIT:
Per Vasily's suggestion in the comments below, I attempted to adapt the "hook and listen" code to my scenario, but was unsuccessful. When I launch my file, I don't even get an exception message in my terminal, I get a Windows pop-up that says Python encountered a problem and needs to quit.
This is how I adapted it:
#[omitting import lines for brevity]
def on_timer():
"""Callback by timer out"""
win32api.PostThreadMessage(main_thread_id, win32con.WM_QUIT, 0, 0);
def on_event(args):
"""Callback for keyboard and mouse events"""
if isinstance(args, KeyboardEvent):
for i in range(1,100):
time.sleep(1)
if args.pressed_key == 'Lcontrol':
break
def init():
hk = Hook()
hk.handler = on_event
main_thread_id = win32api.GetCurrentThreadId()
t = Timer(55.0, on_timer) # Quit after 55 seconds
t.start()
hk.hook(keyboard=True, mouse=True)
At the point when the 3rd party Citrix app begins to launch in my main script, I call hookandlisten.init().
As a reminder, my goal is to wait until the user sends a certain keystroke (here I chose Control) before proceeding with the rest of the main script.
Solved this by eliminating the timer and unhooking the keyboard upon the correct keystroke:
import win32api
import win32con
from pywinauto.win32_hooks import Hook
from pywinauto.win32_hooks import KeyboardEvent
from pywinauto.win32_hooks import MouseEvent
def on_event(args):
"""Callback for keyboard and mouse events"""
if isinstance(args, KeyboardEvent):
if args.current_key == 'Lcontrol' and args.event_type == 'key down':
print("Success")
hk.unhook_keyboard()
return
def init():
hk.handler = on_event
hk.hook(keyboard=True, mouse=False)
hk = Hook()

Categories