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鼠標控制!