1

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

它只工作一次,所以如果我输入例如 $ 它将发送请求,但如果我再次输入它或 * 它不起作用。所以我认为这是因为它打破了循环,因为 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()
4

2 回答 2

0

在 if 和 elif 末尾添加“继续”怎么样?

像这样:

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
于 2021-10-29T17:46:43.903 回答
0

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

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

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

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

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)
于 2021-10-29T18:12:55.093 回答