Is there a way to start a python code automatically when a set of keyboard presses are made?
context:
I want to be able to hit control v (or any other custom key binds) inside a specific folder and the script will run which will result in the picture that I have stored in my clipboard will be automatically made to a jpg.
this is the script that I am using to convert the picture in my clipboard to a png
from PIL import ImageGrab
from datetime import datetime
import os
im = ImageGrab.grabclipboard()
date_now = datetime.now().strftime('%c')
im.save(f'{os.path.dirname(os.path.abspath(__file__))}/{str(date_now)}.png','PNG')
P.S. this is because I am tired of getting a screenshot and then needing to open paint to just image and saving it.
You can do it using another python script that runs all the time:
$pip install keyboard
import keyboard as k
import os
# function to run your python script after keyboard shortcut
def run_script(path_to_file):
os.system("cmd /k python " + path_to_file)
#add hot key for you shortcut
k.add_hotkey('ctrl+shift+a', run_script, args=["enter your path to file here"])
k.wait()
Or else if you are using Windows, create a shortcut for your python script (right click it and then "Create shortcut"), right click the shortcut file you just created and click "Properties", then go to the "Shortcut" tab and click the "Shortcut key:" box, and finally type the combination that you want. if it seems like its not working, than its probably because the python file has no wait on the end of it, so it executes but then immediately closes.
i think this is related to the operating system or window manager you use. For example: in XFCE you'll find it under applications / settings / keyboard / shortcuts. (or something like that.. my desktop is held in German language..)
under Windows you can make a desktop link to your software. When you edit it you can set a shortcut for running this, too.
try to ask google for something like
[your os] shortcut for program
Related
i am trying to make a zoom bot with pyautogui, I have got it working fine in pycharm/running it from the cmd but when i try to run it double clicking the main file everything breaks down. Basically the code is searching for one image using the locateCenterOnScreen() function and clicks it.
# Opening the zoom App
os.popen('C:\\Users\\user\\AppData\\Roaming\\Zoom\\bin\\Zoom.exe')
time.sleep(3)
# Click on join a meeting
join = pyautogui.locateCenterOnScreen('JoinMeeting.png', grayscale=True)
pyautogui.moveTo(join)
pyautogui.click()
time.sleep(3)
So, everything works as intended when on pycharm and when on the folder that the main is running on cmd (using python main.py)
Yet, if I double click the main, it opens the cmd and then crashes saying it cannot locate the image on the locateCenterOnScreen function. My initial thought was that if you double click, it doesn't run where the .png file is and thus doesn't find it, but this can't be because when I run it through cmd it finds the picture perfectly.
I am trying to turn this whole project into .exe to make it usable for more people and this is why i need it to work with double click, because when I turn it into a .exe it will behave the same way.
Thank you
when you double click it uses the default "open with" option, and that might not be python. Python programs need to be opened with python.exe. I believe the default is python launcher.
But if you want to make it into an executable file (.exe), all you need is cx-Freeze. It is an extremely useful tool that turns python codes into exe files. In the end, the effect of double clicking shouldn't matter.
I have cx-Freeze 3.4, and here's a video that explains how to download and use it.
https://www.youtube.com/watch?v=HosXxXE24hA
To address your issue, you could easily change your code to no longer depend on the current work directory but instead locate the files relatively to the path of your script.
Here is an example:
import os
# Get the absolute path of the Python script and extract the directory (dirname)
here = os.path.dirname(os.path.abspath(__file__))
# Concatenate the path with the image name
join_meeting_path = os.path.join(here, 'JoinMeeting.png')
# Opening the zoom App
os.popen('C:\\Users\\user\\AppData\\Roaming\\Zoom\\bin\\Zoom.exe')
time.sleep(3)
# Click on join a meeting
# Use the variable to be independent of the location.
join = pyautogui.locateCenterOnScreen(join_meeting_path, grayscale=True)
pyautogui.moveTo(join)
pyautogui.click()
time.sleep(3)
Let me know if it works for you.
I'm trying to extract the icons from all of the shortcuts in the Start Menu folder. So far I've managed to walk the directory tree, and I just need something to extract the icon from each shortcut. I've tried a few methods suggested across the internet, but I can't seem to make it work fully.
Method 1: Using a program called ResourcesExtract through os.system() to extract the icon from the .lnk file. I soon discovered that this doesn't work for .lnk files, only .exe or .dlls.
import os
os.system(f"resourcesextract.exe /source {shortcut}")
Method 2: Extracting the icon file from the targets of the shortcuts (which can be obtained quite easily using the pywin32 library) using ResourcesExtract. Unfortunately, this only works for some of the programs, due to some shortcuts pointing to .exes without icons.
import os
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
target = shell.CreateShortCut(shortcut).TargetPath
os.system(f"resourcesextract.exe /source {target}")
Method 3: Using pywin32 to get the icon directory. This only works for around 120 of the 300 shortcuts I need it to work on.
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
icon, status = str(shell.CreateShortCut(shortcut).IconLocation).split(",")
I also came across a way to do it using the .NET framework, but I don't know how to interface that with python or if it will even work.
Is anyone aware of a method to extract icons from .lnk files in Python that works on all shortcuts?
import win32com.client
shell = win32com.client.Dispatch("WScript.Shell")
ShortCut = shell.CreateShortCut('example.lnk')
icon_location = ShortCut.IconLocation
It work for me.
I am trying to code a very basic code where I copy some text from one program and then paste it in a different program. I'm not sure how to do this as Pyperclip only seems to paste the text on the command window where I run the code. I want to be able to click on the text-editing program and then have my code paste the text there. I'm attaching my code
import pyperclip
import time
pyperclip.copy('testing')
time.sleep(5)
pyperclip.paste()
When I run this code nothing actually happens. It doesn't paste anything, not even on the command window. I have the sleep function there because that's when I take the time to click on the text-editing program so that Python pastes the text there but it doesn't work.
If all you want to do is copy content to another text editor, then try using pyautogui module. This module allows mouse/keyboard automation via python code.
Code:
import pyautogui
import time
time.sleep(5)
a = "testing"
pyautogui.typewrite(a)
The above code will start typing the word testing after 5 seconds of program execution, so you will have to open your text editor during that duration.
The best part (or the worst) about pyautogui module is that it is focus independent i.e. it works regardless of whether the current application has focus control or not.
Just a sidenote don't use pyperclip for copying/changing/accessing clipboard data, rather try win32clipboard, if you're on windows, as it allows a lot better control over the clipboard.
Although this is a rather old question the answer cost me several hours. My goal was to input a number into another program. That program however is autocompleting the input and therefore using typewrite() (write() in the current version of pyautogui) leads to unexpected behaviour.
However pyautogui helped me in the end, together with pyperclip. Here is the code I am using:
import pyperclip
import time
pyperclip.copy('hello')
time.sleep(5)
with pyautogui.hold('ctrl'):
pyautogui.press(['v'])
This solution is dirty, but it works.
I would like to run my python script while I'm working on other things. For example, I want to run the python script while I'm watching a movie. But I don't want to exit full screen and go to the interactive shell and then go back.
I tried to create a batch file and run from the command line. But it's still not as neat and straight-forward as single-button functionality.
If I want to check the time while I'm watching a movie on hulu website.
python script:
import datetime
datetime.datetime.now()
I wonder if I can set a hotkey so that while I'm on other applications, I can just press the key and then python script will run itself in the background.
Try using keyboard module (allows us to assign custom shortcut keys):
import pyttsx3
import datetime
import keyboard
def time():
engine = pyttsx3.init()
hours = int(datetime.datetime.now().time().hour)%12
if not hours:
hours = 12
engine.say("the time is " + str(hours) + " " + str(datetime.datetime.now().time().minute))
engine.runAndWait()
def keyPress():
keyboard.add_hotkey('+', lambda: time())
keyboard.wait()
keyPress()
WHAT THIS PROGRAM DOES:-
This program a first creates a custom shortcut (assigns it to keyboard key +(change this to whatever hotkey combination you want)). Upon pressing this key, a function called time() gets called, which makes use of windows TTS, to tell your the current time (via voice functionality like siri, alisa etc).
HOW DOES THIS WORK:-
I made use of external libraries keyboard(necessary) and pyttsx3(optional), where the module keyboard allows us to define our custom hotkeys and create a event handler for keyboard events, and pyttsx3 makes use of windows Text to Speech feature to read some text via speech (aka voice). I made use of voice functionality, to not interrupt your flow while your are watching something online.
HOW TO SET IT UP:-
Copy the code, and save it as a .pyw file (notice the w in the
end). The difference between a regular .py an a .pyw file is
that, .py invokes console (~commandline) equivalent tool for
execution and executes in foreground, on the other hand a .pyw
file runs in the background at all times (i.e the console won't show
up). So it won't require you to manually open the console at all
times for executing the script as the script will be running in the
background at all time.
Copy this file (example.pyw) in the startup folder of your OS (any
file in this folder will automatically execute once the operating
system has started). What this will do is when your OS, will boot
your example.pyw file will automatically start executing in the
background, so you won't have to manually launch it at every system
startup. And since it is in the background it won't interfere with
your work. (if you're on windows OS, you can access your startup folder by typing shell:common startup on your run and pressing enter) (adding files to this folder requires root privileges)
HOW TO USE IT:-
While using your system press + (for my case), and your OS will tell you what the current time is. (though it requires your OS to have correct time)
PROS:-
Upon using this for long time I can tell you I never encountered a
single application in which the custom defined hotkey won't work.
Slim to None time required after keypress, for command execution.
A lot resistant to spam of hotkey's. e.x. You may press the
hotkey 100 times but the calls won't be made unless the previous
command has completed execution.
CONS:-
Calling the script for the first time after Bootup, may cause a
little latency in command execution (but only for once, i.e
subsequent calls would be really fast)
P.S:-
It is optional to use pyttsx3, I used it as it makes checking time a lot more easier then reading text or something (at least for me).
Secondly, this process could be made more efficient if you want.
RECOMMENDATIONS:-
Alternatively, If you are familiar with AHK (AutoHotKey) then, doing what i just told on a .ahk script would be a piece of cake, and it's scripts are even faster than my Python one. (Honestly I would definitely Recommend you to use AutoHotKey as it is a really robust language, when it comes to make efficient Operating System scripts)
I am trying to do automatic scene changer in OBS by having a python script search for a specific image on screen. When the image is detected, the python script will send the hotkey, which should be picked by OBS (Same hotkey added in program).
However, I tried this in various applications like chrome/notepad/some games/etc and the hotkeys DO get "transmitted", but OBS doesn't pick them up. I don't know why, any help ?
From this thread: Key Presses in Python
It seems like you need to install pywin32 module.
With that you can send key presses to other applications:
import win32com.client as comclt
wsh= comclt.Dispatch("WScript.Shell")
wsh.AppActivate("Notepad") # select another application
wsh.SendKeys("a") # send the keys you want