I have a program in LabView, which calls some Python Scripts over the cmd line. Those Scripts are for controlling a Electronic Board. After a script is completed, it is closed automatically. The communication is established via a Serial Interface.
My Idea was to initalize the Board Object in a seperate script like so:
#Script for setting a board object
board=ElectronicBoard(com_port="COM5", verbose=True)
if board.is_powered == True:
print("Connected!")
else:
print("Connection failed!")
The other scripts do import that Object and run a function.
Script1:
from Set_Board import board
board.doFunctionX()
board.close()
Script2:
from Set_Board import board
board.doFunctionY()
board.close()
and so on. From Time to time, when running a script, the problem arises, that i cant connect to the Port. Propably beacause it is still in use.
As a solution i was thinking to transfer the Set_Board-script to an .exe, that will run in the background, so the SerialInterface will only be opend once. And not closed and opened time and time again. Right now, that Board Object is only known as long as a Script is opend. What do you think about that?
There has to be an more efficent way for handling this. However, at the moment I just can't see this solution.
Thank you in advance.
For anybody facing the same problem like, where sometimes the Serial-Port remains open, even if it is closed before...
For me, the problem got solved by just clearing the input and output buffer before closing. Also important is to add a larger time delay after the port has been closed, before it can be reopend as Hans Passant stated in his answer: https://stackoverflow.com/a/16777712/19781755