pythonpython-keyboard

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.

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

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()

Solution

  • In this case, there were two issues:

    first, my server wasn't giving any responses, but the code wanted to get a response, so it was waiting a response. So I removed this code on the if and elif part

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

    and secondly, I tried to create two http.client.HTTPConnection() with the same name, so it was giving me an error, so I changed the second to conn2 and same for headers2 and 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)