# Advanced Usage ###### tags: `python` `autohotkey` 這個文件涵蓋著AutoHotkey.py一些進階功能。 ## Threading 在Python中,threading這個模組可以提高應用程式的[響應性](http://terms.naer.edu.tw/detail/19009898/),當後台在執行其它任務的時候,接受使用者輸入的響應性。一個相關的案例就是,一個執行中的I/O與在另一個thread(執行緒)的計算並行執行。這些是實際的OS的執行緒,而不是AHK的偽執行緒([pseudo-threads](https://www.autohotkey.com/docs/misc/Threads.htm))。 AutoHotkey.py從Python透過在AHK中註冊一個[RegisterCallback](https://www.autohotkey.com/docs/commands/RegisterCallback.htm)的callback來呼叫AHK function。這些callback並非是thread-safe([引線安全](http://terms.naer.edu.tw/detail/19431510/))。意思就是當main thread忙著執行AHK function的時候,你從另一個thread再呼叫另一個AHK function的話,就會產生不可預知的結果。它甚至是會讓整個程序崩潰掉。 因此,global AutoHotkey lock (GAL)閃亮亮登場。GAL確保在一個時間點只會有一個OS thread與AHK交互作用。 那,為了能讓後台的thread能夠作業,main thread必需能夠處理Python的程式碼,舉例來說,主動地等待後背的thread完成。不過阿,在main thread呼叫[threading.Thread.join()](https://docs.python.org/3/library/threading.html#threading.Thread.join)還是會阻斷AHK的訊息佇列的處理。這種情況下,AHK就無法處理熱鍵(hotkeys)與其它的回呼(callback)。 相反的,讓AHK利用反覆地呼叫[ahkpy.sleep()](https://ahkpy.readthedocs.io/en/latest/api.html#ahkpy.sleep)來處理它的訊息佇列(message queue),同時檢查後台的thread是否處於活動中: ```python import threading th = threading.Thread(target=some_worker) th.start() while th.is_alive(): ahkpy.sleep(0.01) ``` ## asyncio AutoHotkey.py可以很好的結合[asyncio](https://docs.python.org/3/library/asyncio.html#module-asyncio)一起作業。當你啟動一個長時間執行的迴圈的時候你可以反覆地安排[ahkpy.sleep()](https://ahkpy.readthedocs.io/en/latest/api.html#ahkpy.sleep)的呼叫。這給了AHK時間來處理它的[訊息佇列](http://terms.naer.edu.tw/detail/19385132/): ```python import asyncio import ahkpy async def main(): # Schedule a function that will check AHK message queue repeatedly. loop = asyncio.get_running_loop() loop.call_soon(sleeper, loop) print('Hello ...') await asyncio.sleep(1) print('... World!') def sleeper(loop): ahkpy.sleep(0.01) loop.call_soon(sleeper, loop) asyncio.run(main()) ``` 你可以看一下接收金鑰字串並將之傳給[ahkpy.send()](https://ahkpy.readthedocs.io/en/latest/api.html#ahkpy.send)的[TCP server](https://github.com/Perlence/AutoHotkey.py/blob/master/examples/remote_send.py)的範例。 ## GUI Python原裝提供一個[tkinter](https://docs.python.org/3/library/tkinter.html#module-tkinter)的套件,這是一個Tk GUI toolkit的介面。AutoHotkey.py支援[tkinter](https://docs.python.org/3/library/tkinter.html#module-tkinter),因此可以用它來建立一個使用者介面。 下面是AutoHotkey GUI對應tkinter的控制物件清單([原始AutoHotkey文件連結](https://www.autohotkey.com/docs/commands/GuiControls.htm)): ![](https://hackmd.io/_uploads/SkMHncMj5.png)