Autohotkeyの周りの完全にタイプされたPythonラッパー。
pip install ahk
Python 3.8+が必要です
Autohotkey V1およびV2をサポートします。参照:非パイソン依存関係
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()で停止することができます(積極的にコールバックを積極的に実行することは停止しません)関連するAHKドキュメントも参照してください
Hotstringsは、Hotkeyプロセススレッドに追加することもできます。
通常のAHK文字列の交換をサポートするHotstringsに加えて、Hotstringsトリガーに応じて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 hotstringhotstringsを削除することもできます。
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また、クリップボードの内容が変更されたときに実行するためにコールバックを設定することもできます。上記のHotkeyメソッドと同様に、例外ハンドラーを設定することもできます。 hotkeysと同様に、 on_clipboard_changeコールバックは、有効にするために呼び出されるために.start_hotkeys()も必要です。
コールバック関数は、クリップボードデータ型を示す整数である1つの位置引数を受け入れる必要があります。
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を使用して、HotKeysプロセスに指示を適用するには:
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' )キーが存在しない、または他の問題が発生した場合、例外が提起されます。
このライブラリのほとんどの方法は、非ブロッキングインターフェイスを提供するため、AHKスクリプトが実行されている間、Pythonスクリプトは実行を続けることができます。
デフォルトでは、すべての呼び出しがブロックされています- 各関数は次の関数が実行される前に完全に実行されます。
ただし、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 get_result指定すると、常に特別なFutureResultオブジェクト(または以下で説明するAsync APIのAsyncFutureResultオブジェクト)を受け取ります。関数が通常None返されない場合でも、これはAHKが関数の実行を完了したことを確認するのに役立ちます。
ノンブロッキングコール:
set_coord_mode呼び出しなどから)を継承しないでください。これは、将来のバージョンで変更される場合があります。FutureResultオブジェクト(または以下で説明するAsync 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 Async APIが提供されるため、 async / awaitを使用して関数を呼び出すことができます。同期APIのすべての同じ方法は、ASYNC 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 ())Async APIは、通常のAPIと同一であり、いくつかの顕著な違いがあります。
.mouse_positionや.title for windowsなど)をawaitでいますが、追加の方法( get_mouse_position()やget_title()などが追加され、より直感的なAPIのために追加され、プロパティの使用よりも推奨されます。ahk.mouse_postion = (200, 200) )は、Async API(RuntimeErrorが掲載されています)では許可されていません。同期APIでプロパティセッターは引き続き利用可能です。AsyncFutureResultオブジェクト( blocking=Falseを指定するときに返される)は、 timeoutキーワードがresultメソッドでサポートされていないことを除いて、同期APIのFutureResultオブジェクトと同じ動作します。それも注意してください:
AsyncAHKインスタンスの待望のタスクは同時に実行されません。 Sync APIのように、 blocking=Falseを使用するか、 AsyncAHKの複数のインスタンスを使用する必要があります。このライブラリは完全にヒントされているため、 mypyなどのツールを活用して、コードのタイプ修正性を検証することができます。タイプチェック機能を実装するIDEは、タイプのヒントを活用して、コードが安全であることを確認することもできます。
また、 .ahkスクリプトファイルとして、またはAHKコードを含む文字列として任意のAutoHotkeyコードを実行することもできます。
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キーワード引数を提供するAHK_PATH環境変数を設定しますv2でversionキーワード引数を提供します。例えば:
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に対して設計されており、Function SignaturesはAutohotkey V2を使用している場合でも同じです。ほとんどの動作は同じままですが、V1と比較してAutoHotkey V2を使用すると、一部の動作は変化します。これは、主に2つのバージョン間の根本的な違いによるものです。
このライブラリでAutoHotkey V2を使用するときに経験する顕著な違いのいくつかは次のとおりです。
None返されるのではなく例外を提起します(Autohotkey V2のように、ターゲットエラーは、ウィンドウまたはコントロールが見つからないほとんどの場合に投げられます)controlパラメーターが指定されていない場合、 ControlSend ( ahk.control_sendまたはWindow.sendまたはControl.send )の動作はAutohotkey V2で異なります。 V1では、キーが最上部のコントロールに送信されます。これは通常、正しい動作です。 V2では、キーがウィンドウに直接送信されます。これは、多くの場合、V2を使用するときにコントロールを明示的に指定する必要があることを意味します。TrayTipのsecondstowaitパラメーター( ahk.show_traytip )がV2で削除されました。 Pythonラッパーでこのパラメーターを指定すると、警告が発現され、パラメーターが無視されます。EventではなくV2のデフォルトの送信モードがInputに変更されます(たとえば、 mouse_moveおよびmouse_dragのマウス速度パラメーターは、送信モードが変更されない限りV2で無視されます)2です。 Autohotkey V1で1です。 title_match_modeキーワード引数を使用して、このキーワードwin_get受け入れてこの動作を制御するか、 set_title_match_modeを使用してデフォルトの動作を変更する他のメソッドを使用します(非ブロッキング呼び出しは別々のプロセスで実行され、 set_title_match_modeの影響を受けません) ahkの機能を拡張するための拡張機能を開発できます。つまり、独自のAutoHotkeyコードを作成し、AHKクラスに追加のメソッドを追加できます。詳細については、拡張ドキュメントを参照してください。
すべての貢献は歓迎され、高く評価されています。
フィードバック、アイデア、機能のリクエスト、または質問については、GitHubの問題またはPRを自由に開いてください。
これらは、Pythonでの自動化に一般的に使用されるいくつかの類似のプロジェクトです。
keyboardの作成者から、純粋なPythonマウスコントロール!