我正在尝试做一些python,这个想法是,当按下键盘上的一个特殊键时--这里是$ and *--它将向我的服务器发出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()发布于 2021-10-29 18:12:55
在这种情况下,有两个问题:
首先,我的服务器没有给出任何响应,但是代码想要得到响应,所以它在等待响应。所以我删除了if和elif部分的代码
res = conn.getresponse()
data = res.read()其次,我尝试创建两个同名的http.client.HTTPConnection(),所以它给了我一个错误,所以我将第二个改为conn2,对于headers2和payload2也是如此。
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-29 17:46:43
在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 = Falsehttps://stackoverflow.com/questions/69772812
复制相似问题