Autohotkey周围的完整打字Python包装器。
pip install ahk
需要Python 3.8+
支持Autohotkey V1和V2。另请参阅:非python依赖性
from ahk import AHK
ahk = AHK ()
ahk . mouse_move ( x = 100 , y = 100 , blocking = True ) # Blocks until mouse finishes moving (the default)
ahk . mouse_move ( x = 150 , y = 150 , speed = 10 , blocking = True ) # Moves the mouse to x, y taking 'speed' seconds to move
print ( ahk . mouse_position ) # (150, 150)此软件包可用的某些功能的非详尽示例。有关完整的API参考和其他功能,请参见完整文档。
Hotkeys可以配置为运行Python函数作为回调。
例如:
from ahk import AHK
def my_callback ():
print ( 'Hello callback!' )
ahk = AHK ()
# when WIN + n is pressed, fire `my_callback`
ahk . add_hotkey ( '#n' , callback = my_callback )
ahk . start_hotkeys () # start the hotkey process thread
ahk . block_forever () # not strictly needed in all scripts -- stops the script from exiting; sleep forever现在每当您按+ n , my_callback回调函数将在背景线程中调用。
您还可以为您的回调添加一个异常处理程序:
from ahk import AHK
ahk = AHK ()
def go_boom ():
raise Exception ( 'boom!' )
def my_ex_handler ( hotkey : str , exception : Exception ):
print ( 'exception with callback for hotkey' , hotkey , 'Here was the error:' , exception )
ahk . add_hotkey ( '#n' , callback = go_boom , ex_handler = my_ex_handler )还有删除热键的方法:
# ...
ahk . remove_hotkey ( '#n' ) # remove a hotkey by its keyname
ahk . clear_hotkeys () # remove all hotkeys注意:
ahk.start_hotkeys() )ahk.stop_hotkeys()停止Hotkeys(不会停止积极运行回调)另请参见相关的AHK文档
热弦也可以添加到热键过程线程中。
除了支持普通AHK弦替换的热串外,您还可以提供Python回调(带有可选的异常处理程序)来响应热串触发。
from ahk import AHK
ahk = AHK ()
def my_callback ():
print ( 'hello callback!' )
ahk . add_hotstring ( 'btw' , 'by the way' ) # string replacements
ahk . add_hotstring ( 'btw' , my_callback ) # call python function in response to the hotstring您还可以删除热弦:
ahk . remove_hotstring ( 'btw' ) # remove a hotstring by its trigger sequence
ahk . clear_hotstrings () # remove all registered hotstrings from ahk import AHK
ahk = AHK ()
ahk . mouse_position # Returns a tuple of mouse coordinates (x, y) (relative to active window)
ahk . get_mouse_position ( coord_mode = 'Screen' ) # get coordinates relative to the screen
ahk . mouse_move ( 100 , 100 , speed = 10 , relative = True ) # Moves the mouse reletave to the current position
ahk . mouse_position = ( 100 , 100 ) # Moves the mouse instantly to absolute screen position
ahk . click () # Click the primary mouse button
ahk . click ( 200 , 200 ) # Moves the mouse to a particular position and clicks (relative to active window)
ahk . click ( 100 , 200 , coord_mode = 'Screen' ) # click relative to the screen instead of active window
ahk . click ( button = 'R' , click_count = 2 ) # Clicks the right mouse button twice
ahk . right_click () # Clicks the secondary mouse button
ahk . mouse_drag ( 100 , 100 , relative = True ) # Holds down primary button and moves the mouse from ahk import AHK
ahk = AHK ()
ahk . type ( 'hello, world!' ) # Send keys, as if typed (performs string escapes for you)
ahk . send_input ( 'Hello, {U+1F30E}{!}' ) # Like AHK SendInput
# Unlike `type`, control sequences must be escaped manually.
# For example the characters `!^+#=` and braces (`{` `}`) must be escaped manually.
ahk . key_state ( 'Control' ) # Return True or False based on whether Control key is pressed down
ahk . key_state ( 'CapsLock' , mode = 'T' ) # Check toggle state of a key (like for NumLock, CapsLock, etc)
ahk . key_press ( 'a' ) # Press and release a key
ahk . key_down ( 'Control' ) # Press down (but do not release) Control key
ahk . key_up ( 'Control' ) # Release the key
ahk . set_capslock_state ( "On" ) # Turn CapsLock on
if ahk . key_wait ( 'x' , timeout = 3 ): # wait for a key to be pressed; returns a boolean
print ( 'X was pressed within 3 seconds' )
else :
print ( 'X was not pressed within 3 seconds' )您也可以使用Windows做事。
from ahk import AHK
ahk = AHK ()
win = ahk . active_window # Get the active window
win = ahk . win_get ( title = 'Untitled - Notepad' ) # by title
all_windows = ahk . list_windows () # list of all windows
win = ahk . win_get_from_mouse_position () # the window under the mouse cursor
win = ahk . win_get ( title = 'ahk_pid 20366' ) # get window from pid
# Wait for a window
try :
# wait up to 5 seconds for notepad
win = ahk . win_wait ( title = 'Untitled - Notepad' , timeout = 5 )
# see also: win_wait_active, win_wait_not_active
except TimeoutError :
print ( 'Notepad was not found!' ) from ahk import AHK
ahk = AHK ()
ahk . run_script ( 'Run Notepad' ) # Open notepad
win = ahk . find_window ( title = 'Untitled - Notepad' ) # Find the opened window; returns a `Window` object
# Window object methods
win . send ( 'hello' , control = 'Edit1' ) # Send keys directly to the window (does not need focus!)
# OR ahk.control_send(title='Untitled - Notepad', control='Edit1')
win . move ( x = 200 , y = 300 , width = 500 , height = 800 )
win . activate () # Give the window focus
win . close () # Close the window
win . hide () # Hide the window
win . kill () # Kill the window
win . maximize () # Maximize the window
win . minimize () # Minimize the window
win . restore () # Restore the window
win . show () # Show the window
win . disable () # Make the window non-interactable
win . enable () # Enable it again
win . to_top () # Move the window on top of other windows
win . to_bottom () # Move the window to the bottom of the other windows
win . get_class () # Get the class name of the window
win . get_minmax () # Get the min/max status
win . get_process_name () # Get the process name (e.g., "notepad.exe")
win . process_name # Property; same as `.get_process_name()` above
win . is_always_on_top () # Whether the window has the 'always on top' style applied
win . list_controls () # Get a list of controls (list of `Control` objects)
win . redraw () # Redraw the window
win . set_style ( "-0xC00000" ) # Set a style on the window (in this case, removing the title bar)
win . set_ex_style ( "^0x80" ) # Set an ExStyle on the window (in this case, removes the window from alt-tab list)
win . set_region ( "" ) # See: https://www.autohotkey.com/docs/v2/lib/WinSetRegion.htm
win . set_trans_color ( "White" ) # Makes all pixels of the chosen color invisible inside the specified window.
win . set_transparent ( 155 ) # Makes the specified window semi-transparent (or "Off" to turn off transparency)
win . always_on_top = 'On' # Make the window always on top
# or
win . set_always_on_top ( 'On' )
for window in ahk . list_windows (): # list all (non-hidden) windows -- ``detect_hidden_windows=True`` to include hidden
print ( window . title )
# Some more attributes
print ( window . text ) # window text -- or .get_text()
print ( window . get_position ()) # (x, y, width, height)
print ( window . id ) # the ahk_id of the window
print ( window . pid ) # process ID -- or .get_pid()
print ( window . process_path ) # or .get_process_path()
if win . active : # or win.is_active()
...
if win . exist : # or win.exists()
...
# Controls
edit_control = win . list_controls ()[ 0 ] # get the first control for the window, in this case "Edit1" for Notepad
edit_control . get_text () # get the text in Notepad
edit_control . get_position () # returns a `Postion` namedtuple: e.g. Position(x=6, y=49, width=2381, height=1013)也可以直接调用各种窗口方法,而无需首先使用AHK类上的基础win_*方法创建Window对象。例如,代替上面的win.close() ,可以称呼ahk.win_close(title='Untitled - Notepad') 。
from ahk import AHK
ahk = AHK ()
ahk . image_search ( 'C: \ path \ to \ image.jpg' ) # Find an image on screen
# Find an image within a boundary on screen
ahk . image_search ( 'C: \ path \ to \ image.jpg' , upper_bound = ( 100 , 100 ), # upper-left corner of search area
lower_bound = ( 400 , 400 )) # lower-right corner of search area
ahk . pixel_get_color ( 100 , 100 ) # Get color of pixel located at coords (100, 100)
ahk . pixel_search ( color = '0x9d6346' , search_region_start = ( 0 , 0 ), search_region_end = ( 500 , 500 )) # Get coords of the first pixel with specified color 获取/设置Clipboard数据
from ahk import AHK
ahk = AHK ()
ahk . set_clipboard ( 'hello N{EARTH GLOBE AMERICAS} ' ) # set clipboard text contents
ahk . get_clipboard () # get clipboard text contents
# 'hello ?'
ahk . set_clipboard ( "" ) # Clear the clipboard
ahk . clip_wait ( timeout = 3 ) # Wait for clipboard contents to change (with text or file(s))
ahk . clip_wait ( timeout = 3 , wait_for_any_data = True ) # wait for _any_ clipboard contents您也可以获取/设置ClipboardAll - 但是,除了get_clipboard_all返回或可能发生意外问题外,您绝对不要尝试使用其他任何数据来调用set_clipboard_all 。
from ahk import AHK
ahk = AHK ()
# save all clipboard contents in all formats
saved_clipboard = ahk . get_clipboard_all ()
ahk . set_clipboard ( 'something else' )
...
ahk . set_clipboard_all ( saved_clipboard ) # restore saved content from earlier当剪贴板内容更改时,您还可以设置一个回调以执行。与上面提到的热键方法一样,您还可以设置一个异常处理程序。像hotkeys一样, on_clipboard_change回调也需要.start_hotkeys()才能生效。
回调函数必须接受一个位置参数,该参数是指示剪贴板数据类型的整数。
from ahk import AHK
ahk = AHK ()
def my_clipboard_callback ( change_type : int ):
if change_type == 0 :
print ( 'Clipboard is now empty' )
elif change_type == 1 :
print ( 'Clipboard has text contents' )
elif change_type == 2 :
print ( 'Clipboard has non-text contents' )
ahk . on_clipboard_change ( my_clipboard_callback )
ahk . start_hotkeys () # like with hotkeys, must be called at least once for listening to start
# ...
ahk . set_clipboard ( "hello" ) # will cause the message "Clipboard has text contents" to be printed by the callback
ahk . set_clipboard ( "" ) # Clears the clipboard, causing the message "Clipboard is now empty" to be printed by the callback from ahk import AHK
ahk = AHK ()
ahk . sound_play ( 'C: \ path \ to \ sound.wav' ) # Play an audio file
ahk . sound_beep ( frequency = 440 , duration = 1000 ) # Play a beep for 1 second (duration in microseconds)
ahk . get_volume ( device_number = 1 ) # Get volume of a device
ahk . set_volume ( 50 , device_number = 1 ) # Set volume of a device
ahk . sound_get ( device_number = 1 , component_type = 'MASTER' , control_type = 'VOLUME' ) # Get sound device property
ahk . sound_set ( 50 , device_number = 1 , component_type = 'MASTER' , control_type = 'VOLUME' ) # Set sound device property 工具提示/托盘
import time
from ahk import AHK
ahk = AHK ()
ahk . show_tooltip ( "hello4" , x = 10 , y = 10 )
time . sleep ( 2 )
ahk . hide_tooltip () # hide the tooltip
ahk . show_info_traytip ( "Info" , "It's also info" , silent = False , blocking = True ) # Default info traytip
ahk . show_warning_traytip ( "Warning" , "It's a warning" ) # Warning traytip
ahk . show_error_traytip ( "Error" , "It's an error" ) # Error trytip对话框
from ahk import AHK , MsgBoxButtons
ahk = AHK ()
ahk . msg_box ( text = 'Do you like message boxes?' , title = 'My Title' , buttons = MsgBoxButtons . YES_NO )
ahk . input_box ( prompt = 'Password' , title = 'Enter your password' , hide = True )
ahk . file_select_box ( title = 'Select one or more mp3 files' , multi = True , filter = '*.mp3' , file_must_exist = True )
ahk . folder_select_box ( prompt = 'Select a folder' )您可以更改各种全球状态,例如CoordMode , DetectHiddenWindows等
from ahk import AHK
ahk = AHK ()
ahk . set_coord_mode ( 'Mouse' , 'Screen' ) # set default Mouse CoordMode to be relative to Screen
ahk . set_detect_hidden_windows ( True ) # Turn on detect hidden windows by default
ahk . set_send_level ( 5 ) # Change send https://www.autohotkey.com/docs/v1/lib/SendLevel.htm
ahk . set_title_match_mode ( 'Slow' ) # change title match speed and/or mode
ahk . set_title_match_mode ( 'RegEx' )
ahk . set_title_match_mode (( 'RegEx' , 'Slow' )) # or both at the same time
ahk . set_send_mode ( 'Event' ) # change the default SendMode 您可以添加将添加到所有生成脚本的指令。例如,为防止Ahk Trayicon出现,您可以添加Notrayicon指令。
from ahk import AHK
from ahk . directives import NoTrayIcon
ahk = AHK ( directives = [ NoTrayIcon ])默认情况下,会自动添加一些指令以确保功能并与任何用户提供的指令合并。
默认情况下,未用于处理热键和热串(下文讨论)的AHK过程。使用关键字参数apply_to_hotkeys_process=True :
from ahk import AHK
from ahk . directives import NoTrayIcon
directives = [
NoTrayIcon ( apply_to_hotkeys_process = True )
]
ahk = AHK ( directives = directives )如上所述,如果需要,您可以隐藏托盘图标。此外,还有一些可自定义托盘图标的方法。
from ahk import AHK
ahk = AHK ()
# change the tray icon (in this case, using a builtin system icon)
ahk . menu_tray_icon ( 'Shell32.dll' , 174 )
# revert it back to the original:
ahk . menu_tray_icon ()
# change the tooltip that shows up when hovering the mouse over the tray icon
ahk . menu_tray_tooltip ( 'My Program Name' )
# Hide the tray icon
ahk . menu_tray_icon_hide ()
# Show the tray icon that was previously hidden by ``NoTrayIcon`` or ``menu_tray_icon_hide``
ahk . menu_tray_icon_show ()您可以读取/写入/删除注册表键:
from ahk import AHK
ahk = AHK ()
ahk . reg_write ( 'REG_SZ' , r'HKEY_CURRENT_USERSOFTWAREmy-software' , value = 'test' )
ahk . reg_write ( 'REG_SZ' , r'HKEY_CURRENT_USERSOFTWAREmy-software' , value_name = 'foo' , value = 'bar' )
ahk . reg_read ( r'HKEY_CURRENT_USERSOFTWAREmy-software' ) # 'test'
ahk . reg_delete ( r'HKEY_CURRENT_USERSOFTWAREmy-software' )如果键不存在或发生其他问题,则会提出异常。
该库中的大多数方法都提供非阻止接口,因此您的Python脚本可以在您的AHK脚本运行时继续执行。
默认情况下,所有呼叫都在阻止- 每个函数将在下一个函数运行之前完全执行。
但是,有时您可能需要在AHK执行一些代码时运行其他代码。当blocking关键字参数提供False时,函数调用将立即返回,而AHK函数在后台进行。
例如,您可以缓慢移动鼠标并报告其移动时的位置:
import time
from ahk import AHK
ahk = AHK ()
ahk . mouse_position = ( 200 , 200 ) # Moves the mouse instantly to the start position
start = time . time ()
# move the mouse very slowly
ahk . mouse_move ( x = 100 , y = 100 , speed = 30 , blocking = False )
# This code begins executing right away, even though the mouse is still moving
while True :
t = round ( time . time () - start , 4 )
position = ahk . mouse_position
print ( t , position ) # report mouse position while it moves
if position == ( 100 , 100 ):
break当您指定blocking=False时,您将始终接收一个特殊的FutureResult对象(或下面讨论的异步API中的AsyncFutureResult对象),它允许您等待该函数通过get_result函数完成并检索返回值。即使函数通常None返回,这对于确保AHK完成了该功能也很有用。
非块电话:
set_coord_mode调用或类似) - 这可能会在将来版本中发生变化。FutureResult对象(或下面讨论的异步API中的AsyncFutureResult对象),该对象可让您等待该函数完成并通过result函数检索返回值。即使函数通常None返回,这对于确保AHK完成了该功能也很有用。 from ahk import AHK
ahk = AHK ()
future_result = ahk . mouse_move ( 100 , 100 , speed = 40 , blocking = False )
...
# wait on the mouse_move to finish
future_result . result ( timeout = 10 ) # timeout keyword is optional 提供异步API,因此可以使用async / await功能调用功能。同步API的所有相同方法都在异步API中可用。
from ahk import AsyncAHK
import asyncio
ahk = AsyncAHK ()
async def main ():
await ahk . mouse_move ( 100 , 100 )
x , y = await ahk . get_mouse_position ()
print ( x , y )
asyncio . run ( main ())异步API与正常API相同,存在一些明显的差异:
await属性(例如.mouse_position或.title ),但已添加了其他方法(例如get_mouse_position()和get_title() )以进行更直观的API,并建议使用属性。ahk.mouse_postion = (200, 200) )(提高了RuntimeError)。属性设置器在同步API中仍然可用。AsyncFutureResult对象(指定blocking=False时返回)与同步API中的FutureResult对象相同,但result方法不支持timeout关键字)。还请注意:
AsyncAHK实例上的期待任务不会同时运行。您必须使用blocking=False ,例如在同步API中,或使用AsyncAHK的多个实例。该库是完全类型的建筑物,使您能够利用mypy等工具来帮助验证代码的类型校正性。实现类型检查功能的IDE也能够利用类型提示,以帮助确保您的代码安全。
您还可以将任意Autohotkey代码作为.ahk脚本文件或包含AHK代码的字符串运行。
from ahk import AHK
ahk = AHK ()
my_script = '''
MouseMove, 100, 100
; etc...
'''
ahk . run_script ( my_script ) from ahk import AHK
ahk = AHK ()
script_path = r'C:PathTomyscript.ahk'
ahk . run_script ( script_path )要使用此软件包,您需要AutoHotkey可执行文件(例如, AutoHotkey.exe )。预计默认情况下或默认安装位置( C:Program FilesAutoHotkeyAutoHotkey.exe for V1或C:Program FilesAutoHotkeyv2AutoHotkey64.exe for V2)
Autohotkey V1和V2都得到了充分的支持,尽管将根据您使用的版本发生某些行为差异。请参阅下面的注释。
提供Autohotkey二进制的推荐方法(对于V1和V2)是为此软件包安装binary额外的方法。这将提供必要的可执行文件,并帮助确保将它们正确放置在路径上。
pip install "ahk[binary]"
另外,您可以提供代码中的路径:
from ahk import AHK
ahk = AHK ( executable_path = 'C: \ path \ to \ AutoHotkey.exe' )您还可以使用AHK_PATH环境变量来指定可执行的位置。
set AHK_PATH=C:PathToAutoHotkey.exe
python myscript.py 默认情况下,当未设置没有executable_path参数(或AHK_PATH环境变量)时,仅在路径或默认安装位置上搜索AutoHotkey V1二进制名称。此行为可能会在将来的版本中发生变化,以允许默认情况下使用V2。
要使用Autohotkey版本2,您可以执行以下任何操作:
executable_path关键字参数,并带有autohotkey v2二进制的位置AHK_PATH环境变量version关键字参数为VALUE v2提供,该参数使使用Autohotkey V2二进制名称和默认安装位置找到可执行文件。例如:
from ahk import AHK
ahk = AHK ( executable_path = r'C:Program FilesAutoHotkeyv2AutoHotkey64.exe' )
# OR
ahk = AHK ( version = 'v2' )当您提供version关键字参数(使用"v1"或"v2" )时,进行了检查,以确保提供的(或发现)二进制的二进制匹配所请求的版本。省略version关键字时,将自动从提供(或发现)可执行的二进制文件确定版本。
该项目的API最初是针对Autohotkey V1设计的,即使使用Autohotkey V2,功能签名也相同。尽管大多数行为保持不变,但与V1相比,使用Autohotkey V2时确实有些行为会发生变化。这主要是由于两个版本之间的潜在差异。
在此库中使用Autohotkey V2时,您可能会遇到的一些显着差异包括:
None (如在Autohotkey V2中,在找不到窗口或控件的大多数情况下,都会抛出目标eRROR)control参数时, ControlSend ( ahk.control_send或Window.send或Control.send )的行为在Autohotkey V2中有所不同。在V1中,将键发送到最顶部的控件,这通常是正确的行为。在V2中,键直接发送到窗口。这意味着在许多情况下,您需要在使用V2时明确指定控件。TrayTip的secondstowait stowaitparamater( ahk.show_traytip )在V2中删除。在Python包装器中指定此参数将导致发出警告,并忽略该参数。Input而不是V1中的Event (例如,除非更改了发送模式,否则在V2中忽略鼠标速度参数为mouse_move和mouse_drag )2 。在Autohotkey V1中为1 。使用title_match_mode关键字参数对win_get和其他接受此关键字控制此行为或使用set_title_match_mode更改默认行为的方法(非块调用是在单独的进程中运行的,并且不受set_title_match_mode的影响) 您可以开发扩展ahk功能的扩展名 - 也就是说:编写自己的Autohotkey代码并在AHK类中添加其他方法。有关更多信息,请参见扩展文档。
所有贡献都受到欢迎和赞赏。
请随时打开GitHub问题或公关以获取反馈,想法,功能请求或问题。
这些是一些与Python自动化的类似项目。
keyboard的创建者,纯Python鼠标控制!