[英]keyboard.is_pressed() breaking the loop
I'm trying to do some python, the idea is that when a special key on the keyboard is pressed in this case $ and * it will make a web request to my server.我正在尝试做一些python,这个想法是当键盘上的一个特殊键在这种情况下被按下时 $ 和 * 它将向我的服务器发出一个网络请求。
It works but only once, so if I type for example $ it will send the request, but if I type this again or * it doesn't work.它只工作一次,所以如果我输入例如 $ 它会发送请求,但如果我再次输入它或 * 它不起作用。 So I think it's because it's breaking the loop because of the keyboard.is_pressed() and I don't know how to fix that所以我认为这是因为它因为 keyboard.is_pressed() 而打破了循环,我不知道如何解决这个问题
Here's the code:这是代码:
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()
How about adding 'continue' at the end of your if and elif?在 if 和 elif 的末尾添加“继续”怎么样?
like this:像这样:
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
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.