1

I have the following Python code which is just reading from an Arduino, and writing to a file:

import serial
from datetime import datetime
import time

ser = serial.Serial('COM3', 9600, timeout=0)

text_file = open("voltages.txt", 'w') 

while 1:
    x=ser.readline()
    print(str(datetime.now()), x) 
    data = [str(datetime.now()),x]
    text_file.write("{}\n".format(data))
    text_file.flush()
    time.sleep(1)

Whenever I interrupt the script, I always have to type ser.close() in the console, otherwise I cannot start the script again (in the same console).

How can I close the serial communication automatically whenever I interrupt the script?

2 Answers 2

4

You can use the with statement.

import serial
from datetime import datetime
import time

with serial.Serial('COM3', 9600, timeout=0) as ser, open("voltages.txt", 'w') as text_file:
    while True:
        x=ser.readline()
        print(str(datetime.now()), x) 
        data = [str(datetime.now()),x]
        text_file.write("{}\n".format(data))
        text_file.flush()
        time.sleep(1)

The with statement will automatically close ser and text_file when execution leaves the with statement. This can be an exception in your case. The with statement has been introduced by PEP 343 to remove try/finaly statements by using context managers.

Sign up to request clarification or add additional context in comments.

Comments

3

Use a try/finally block to insure close is called:

try:
    while 1:
        x = ser.readline()
        ....
finally:
    ser.close()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.