メイン画像

PyAutoGUI高速化

PyAutoGUI高速化


標準ではpyautoguiでキー操作を高速でやろうと思っても処理に0.1秒以上かかってしまい、思うほど高速で押せない。
ライブラリを直接修正して高速化してみます。
高速化で調べるとMACでやってる人はいたけどWINDOWSでは見当たらなかったのと該当箇所の修正が違うのでWINDOWSでやるための修正箇所を探しました。
macならば_pyautogui_osx.py内のsleepを無くしてやれば良いみたいです。Windowsでは_pyautogui_win.pyの_keyUp、_keydown関数内で呼ばれているisShiftCharacter関数(__init__.py)でsleepっぽいのがあるのでそこみたいでした。
__init__.py内のisShiftCharacter関数がキー操作時に呼ばれているのでそこのPAUSEを0.1から0に変更してやります。

__init__.py
def isShiftCharacter(character):
    """
    Returns True if the ``character`` is a keyboard key that would require the shift key to be held down, such as
    uppercase letters or the symbols on the keyboard's number row.
    """
    # NOTE TODO - This will be different for non-qwerty keyboards.
    return character.isupper() or character in set('~!@#$%^&*()_+{}|:"<>?')


# The platformModule is where we reference the platform-specific functions.
if sys.platform.startswith("java"):
    # from . import _pyautogui_java as platformModule
    raise NotImplementedError("Jython is not yet supported by PyAutoGUI.")
elif sys.platform == "darwin":
    from . import _pyautogui_osx as platformModule
elif sys.platform == "win32":
    from . import _pyautogui_win as platformModule
elif platform.system() == "Linux":
    from . import _pyautogui_x11 as platformModule
else:
    raise NotImplementedError("Your platform (%s) is not supported by PyAutoGUI." % (platform.system()))

# TODO: Having module-wide user-writable global variables is bad. It makes
# restructuring the code very difficult. For instance, what if we decide to
# move the mouse-related functions to a separate file (a submodule)? How that
# file will access this module vars? It will probably lead to a circular
# import.

# In seconds. Any duration less than this is rounded to 0.0 to instantly move
# the mouse.
MINIMUM_DURATION = 0.1
# If sleep_amount is less than MINIMUM_DURATION, time.sleep() will be a no-op and the mouse cursor moves there instantly.
# TODO: This value should vary with the platform. http://stackoverflow.com/q/1133857
MINIMUM_SLEEP = 0.05

# The number of seconds to pause after EVERY public function call. Useful for debugging:
PAUSE = 0.1  # Tenth-second pause by default.


ライブラリの場所は↓で表示できます。

test.py
import pyautogui as pgui

if __name__ == '__main__':
    print(f'{pgui.__file__=}')

これでライブラリの場所が出るのでそこにある

これでキー操作時に毎回0.1秒の待ちが入っていたのがなくなったのでかなり高速に動くようになりました。
ただ、この待ちをなくすとMACではシフトキーとかがうまく動かなくなるらしいのでwindowsでも同じような症状が出るかもしれません。検証はしていないので詳細は不明です。

アカウントを作成 して、もっと沢山の記事を読みませんか?


この記事が気に入ったら Sylphy さんを応援しませんか?
メッセージを添えてチップを送ることができます。


この記事にコメントをしてみませんか?


プログラミング、ジャンク品修理、ゲームなどの趣味の部分を主に取り扱っていきます。

おすすめの記事