File indexing completed on 2025-01-19 06:55:04
0001 #!/usr/bin/env python 0002 0003 import sys, kmuddy 0004 0005 # Set this to False to use the tuple / loop approach 0006 # In your own scripts you are actually free to use both at the same time 0007 UseCallbacks = True 0008 0009 # An ordinary signal handler that just prints out the text received from 0010 # KMuddy 0011 def status_handler(line): 0012 sys.stdout.write("Event: %s\n" % line) 0013 sys.stdout.flush() 0014 0015 # This handler returns a value (not None) and will cause wait4Event() to 0016 # abort execution and return this value. Use this for clean script 0017 # termination, although it's little more than a style thing. 0018 # 0019 # It absolutely works if you just bail out whenever you want without 0020 # ever calling closeSocket() 0021 def status_handler_final(line): 0022 sys.stdout.write("Final Event: %s\n" % line) 0023 sys.stdout.flush() 0024 return True 0025 0026 if __name__ == "__main__": 0027 sys.stdout.write("KMuddy Python Test v1.0\n") 0028 # IMPORTANT: ALWAYS flush() your output streams if you want to 0029 # write data back to KMuddy. 0030 # Also remember that for this to actually do something you also have to 0031 # check any of: 0032 # "Enable script output" / "Enable error output" / 0033 # / "Send script output" / "Send error output" 0034 # in the script properties within KMuddy. 0035 sys.stdout.flush() 0036 # Initialize KMuddy socket 0037 # This requires "Communicate variables" being checked in the script 0038 # properties. 0039 kmuddy.initSocket() 0040 if UseCallbacks == True: 0041 # Approach 1: Attach event handling functions to TCP ports 0042 kmuddy.registerEvent(1234, status_handler) 0043 kmuddy.registerEvent(2345, status_handler_final) 0044 # Enter event loop 0045 kmuddy.wait4Event() 0046 else: 0047 # Approach 2: Register events on TCP ports 0048 kmuddy.registerEvent(1234) 0049 kmuddy.registerEvent(2345) 0050 # ...and let wait4Event() return a list of tuples of (port, data_string) 0051 while 1: 0052 evts = kmuddy.wait4Event() 0053 for evt in evts: 0054 sys.stderr.write("Event on port %d: %s" % evt) 0055 sys.stderr.flush() 0056 kmuddy.closeSocket() 0057