やみとものプログラミング日記 やみとものプログラミング日記
TOP 【Python】モールス信号でパソコンを操作してみた
【Python】モールス信号でパソコンを操作してみた

【Python】モールス信号でパソコンを操作してみた

Python プログラミング
作成日時: 2020年5月1日
更新日時: 2020年5月1日

コード

from pynput.keyboard import Key, Listener
import time
import webbrowser


pre_press_time = None
codes = []
start = False

def on_press(key):
    global pre_press_time

    if key == Key.alt:
        pre_press_time = time.time()

def on_release(key):
    global start, codes

    if key == Key.alt:
        press_time = time.time() - pre_press_time
        print(press_time)

        if press_time > 0.1:
            print("M")
            codes.append(1)
        else:
            print("m")
            codes.append(0)

        if not start and codes[-3:] == [0, 0, 0]:
            print("MOAI START\a\a\a")
            start = True
            codes = []
        elif start and codes[-3:] == [1, 1, 1]:
            print("MOAI END\a")
            start = False
            codes = []
        elif start and codes[-2:] == [1, 0]:
            webbrowser.open("https://www.google.co.jp")

if __name__ == '__main__':
    try:
        with Listener(on_press=on_press, on_release=on_release) as listener:
            listener.join()
    except:
        pass

注意 & 使い方

注意

Macでしか動作検証していません。
root権限で起動する必要があります。
alt以外で操作したい場合はkey.charで文字を取得してください。
足りないモジュールはpip等でインストールしてください。

使い方

「・・・」(altキーを短く3回打つ)で起動。ビープ音が3回なります。
「- - -」(altキーを少し長めに3回打つ)で終了。(プログラムが終了するわけではない)
「- ・」(altキーを長めに打った後即座に短く1回)でgoogleを開きます。