keyboard.is_pressed() 打破循环

keyboard.is_pressed() breaking the loop

我正在尝试做一些事情 python,想法是当按下键盘上的一个特殊键时 $ 和 * 它将向我的服务器发出一个网络请求。

它只工作一次,所以如果我输入例如 $ 它会发送请求,但如果我再次输入或 * 它就不起作用。所以我认为这是因为 keyboard.is_pressed() 打破了循环,我不知道如何解决

代码如下:

import http.client
import keyboard

while True:
    if keyboard.is_pressed('*'):
        conn = http.client.HTTPConnection('server_ip:server_port')
        payload = "{\n\t\"value\" : 0\n}"
        headers = {'Content-Type': "application/json",'Accept': "application/json"}
        conn.request("POST", "/api", payload, headers)
        res = conn.getresponse()
        data = res.read()

    elif keyboard.is_pressed('$'):
        conn = http.client.HTTPConnection('server_ip:server_port')
        payload = "{\n\t\"value\" : 1\n}"
        headers = {'Content-Type': "application/json",'Accept': "application/json"}
        conn.request("POST", "/api", payload, headers)
        res = conn.getresponse()
        data = res.read()

在 if 和 elif 的末尾添加 'continue' 怎么样?

像这样:

import http.client
import keyboard
import time

keep_looping = True
while keep_looping:
    if keyboard.is_pressed('*'):
        conn = http.client.HTTPConnection('server_ip:server_port')
        payload = "{\n\t\"value\" : 0\n}"
        headers = {'Content-Type': "application/json",'Accept': "application/json"}
        conn.request("POST", "/api", payload, headers)
        res = conn.getresponse()
        data = res.read()
        time.sleep(0.5)

    elif keyboard.is_pressed('$'):
        conn = http.client.HTTPConnection('server_ip:server_port')
        payload = "{\n\t\"value\" : 1\n}"
        headers = {'Content-Type': "application/json",'Accept': "application/json"}
        conn.request("POST", "/api", payload, headers)
        res = conn.getresponse()
        data = res.read()
        time.sleep(0.5)

    elif keyboard.is_pressed('/'):  # Add this in so you can stop the loop when needed. Use any keypress you like.
        keep_looping = False

在这种情况下,有两个问题:

首先,我的服务器没有给出任何响应,但代码想要获得响应,所以它正在等待响应。所以我在 if 和 elif 部分删除了这段代码

 res = conn.getresponse()
    data = res.read()

其次,我尝试创建两个具有相同名称的 http.client.HTTPConnection(),所以它给了我一个错误,所以我将第二个更改为 conn2headers2payload2

相同
import http.client
import keyboard
import time

while True:
    if keyboard.is_pressed('Page_Up'):
        conn = http.client.HTTPConnection('server_ip:server_port')
        headers = {'Content-Type': "application/json",'Accept': "application/json"}
        payload = "{\n\t\"value\" : 0\n}"
        conn.request("POST", "/api", payload, headers)
        time.sleep(0.5)

    elif keyboard.is_pressed('Page_Down'):
        conn2 = http.client.HTTPConnection('server_ip:server_port')
        headers2 = {'Content-Type': "application/json",'Accept': "application/json"}
        payload2 = "{\n\t\"value\" : 1\n}"
        conn2.request("POST", "/api", payload2, headers2)
        time.sleep(0.5)