If you're looking to be able to run a python function from within an xml file, take a look at this: lxml extension functions
With these, you can define a function namespace and then, with the proper editing of your xml/xsl file, you'll be able to put the value of your code into the xml file.
The other option would be to do as systempuntoout suggested and parse your xml into a python object using the lxml library, and then place the output of running your code in the proper place.
Either way, more specificity in your question will help us answer you quickly and correctly.
Edit:
If you're just looking to write the keystrokes to some file.xml, you can use:
with open('file.xml', 'w') as f:
f.write(keystroke_data)