我正在尝试做一些python,这个想法是,当键盘上的一个特殊键被按下时,在这种情况下$和*它会向我的服务器发出web请求。
它工作,但只有一次,所以如果我输入例如$,它会发送请求,但如果我再次输入this或*,它不工作。所以我认为这是因为它打破了循环因为keyboard。is_pressed()我不知道如何修复
代码如下:
import http.client
import keyboard
while True:
if keyboard.is_pressed('*'):
conn = http.client.HTTPConnection('server_ip:server_port')
payload = "{nt"value" : 0n}"
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 = "{nt"value" : 1n}"
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 = "{nt"value" : 0n}"
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 = "{nt"value" : 1n}"
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()所以它给了我一个错误,所以我把第二个改为conn2headers2也一样和payload2import 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 = "{nt"value" : 0n}"
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 = "{nt"value" : 1n}"
conn2.request("POST", "/api", payload2, headers2)
time.sleep(0.5)