Home > Back-end >  Execute an event if event.code is an attribute in an XML file
Execute an event if event.code is an attribute in an XML file

Time:06-24

I have this xmlfile.xml:

<events>
   <event id="30">
      <event_cod>30</event_cod>
      <event_key>KEY_A</event_key>
   </event>

   <event id="23">
      <event_cod>23</event_cod>
      <event_key>KEY_I</event_key>
   </event>

   <event id="16">
      <event_cod>16</event_cod>
      <event_key>KEY_Q</event_key>
   </event>
</events>

I have device, and when I press a key, that device generates an event_code (30, 23, 16 etc.)

device = evdev.InputDevice('/dev/input/eventX')

for event in device.read_loop():

 if event.value == 1:
 
    import xml.etree.ElementTree as ET
    tree = ET.parse('/xmlfile.xml')
    
    for child in tree.getroot():
      for core in child:
        core_value = str(core.text)
 
        if event.code == ????????(core_value = 30, 23, 16 etc.):
               get_xml = ET.parse('/xmlfile.xml')
               xml_content = get_xml.getroot()
               print('You Pressed "   xml_content[0][1].text   " Key!')

It is my first time when I programming in Python (I am PHP guy...), and at this point I'm stuck :(

Can you please help me how to solve that for each item in XML to generate that

if event.code == ... 

CodePudding user response:

This does not exactly answer your question to create event handlers, but from the general code I inferred that you may like this approach.

Very comfortably you can use lxml with an XPath predicate to match the elements of your XML file:

import evdev
import lxml.etree as ET

tree = ET.parse('xmlfile.xml')
device = evdev.InputDevice('/dev/input/event2')
print(device)

for event in device.read_loop():
    if event.value == 1:
        res = tree.xpath('/events/event[@id=' repr(event.code) ']/event_key')    
        if len(res) > 0:
            print('You Pressed '   res[0].text   ' Key!')

In the above code, the XML file xmlfile.xml is parsed and then queried with the XPath-1.0 expression

/events/event[@id=' repr(event.code) ']/event_key

where repr transforms then event.code to a string value. The predicate [@id=...] selects the appropriate event node and then gets its event_key elements - which is a list. After that, if present, the first item of this list is selected by res[0] and its text value, respectively, by res[0].text. The length check for res is done to assure that a matching entry is present in your XML file.

The example works with the keyboard device as an example.

  • Related