Is it possible to have EventHandlers in Python like C#.
In C# I have an Event Handler for receiving data over a serial port, this stops the need for listening in a loop.
Like this:
private void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
InputData = ComPort.ReadExisting();
if (InputData != String.Empty)
{
BeginInvoke(new SetTextCallback(SetText), new object[] { InputData });
if (InputData == "0")
{
WriteToLog("COM IN = 0 GetFileNames");
GetFileNames();
}
if (InputData == "1")
{
WriteToLog("COM IN = 1 GetFileCount");
GetFileCount();
}
if (InputData == "2")
{
WriteToLog("COM IN = 2 GetFolderSize");
GetFolderSize();
}
if (InputData == "3")
{
WriteToLog("COM IN = 3 Restart PC");
RestartPC();
}
}
}
Is there any analogous way of doing this in python? as currently I am listening like this and it seems wasteful as it's just sitting there ticking away.
import time
import serial
ser = serial.Serial(
port='/dev/ttyUSB0',
baudrate = 9600,
parity=serial.PARITY_NONE,
stopbits=serial.STOPBITS_ONE,
bytesize=serial.EIGHTBITS,
timeout=1
)
counter=0
while 1:
x=ser.readline()
print x