0

I tried to use pySerial to build a simple terminal to interact COM1 in my PC,

I create 2 threads , one is for READ , the other is for Write

however,

def write_comport():
    global  ser,cmd, log_file
    print("enter Q to quit")
    while True:
        cmd = raw_input(">>:")
        # print(repr(var))

        if cmd=='Q':
            ser.close()
            sys.exit()
            log_file.close()
        else:
            ser.write(cmd + '\r\n')
            write_to_file("[Input]"+cmd, log_file)
            time.sleep(1)
        pass


def read_comport():
    global ser, cmd, log_file
    while True:
        element = ser.readline().strip('\n')
        if "~ #" in str(element):
            continue
        if cmd == str(element).strip():
            continue
        if "img" in str(element):
            print("got:"+element)
            beep()

        print element
        write_to_file(cmd, log_file)


    pass
def write_to_file(str,f):
    f.write(str)
    f.flush

def main():
    try:
        global read_thr,write_thr
        beep()
        port_num='COM4'
        baudrate=115200
        init_serial_port(port_num,baudrate)
        read_thr =Thread(target=read_comport)
        read_thr.start()
        write_thr =Thread(target=write_comport)
        write_thr.start()

        while True:
            pass
    except Exception as e:
        print(e)
        exit_prog()

but the behavior of my code is not as smart as putty or anyother. cause my function can Not detect whenever the reader is done. is there any better way to achieve this goal?

By the way, I tried to save the log into txt file real-time . But when I open the file during the process is running, it seems nothing write to my text log file?

newBike
  • 14,385
  • 29
  • 109
  • 192
  • What version of Python are you using ? (I see it's 3.x but I am curious if it's 3.3) – P_Rein Apr 16 '13 at 06:19
  • I don't know how else to contact you .. so.. could you help with [this problem](http://stackoverflow.com/questions/16017288/using-pyserial-with-python-3-3) as it seems you have the answer to that. On your problem.. have you tried flushing the log_file after each write ? – P_Rein Apr 16 '13 at 08:18
  • Was this ever solved because i am having a similar problem, also you forgot the brackets for print elements in your read_comport() function – hamsolo474 - Reinstate Monica Mar 09 '16 at 08:58

0 Answers0