Python脚本读取串口,输出到文本文件

时间:2015-06-25 13:31:08

标签: python

我正在尝试从串口读取输出并将其写入文本文件。到目前为止,这连接并打印输出,但我无法弄清楚如何将输出发送到文本文件(首选csv文件)。

#! /usr/bin/env python3
import serial
import csv
import sys
import io

#excel stuff
#from time import gmtime, strftime
#resultFile=open('MyData.csv','wb')
#end excel stuff

def scan():
    """scan for available ports. return a list of tuples (num, name)"""
    available = []
    for i in range(256):
        try:
            s = serial.Serial(i)
            available.append( (i, s.portstr))
            s.close()   # explicit close 'cause of delayed GC in java
        except serial.SerialException:
            pass
    return available
if __name__=='__main__':
    print ("Found ports:")
    for n,s in scan():
        print ("(%d) %s" % (n,s))
    selection = input("Enter port number:")
    try:
        ser = serial.Serial(eval(selection), 9600, timeout=1)
        print("connected to: " + ser.portstr)
    except serial.SerialException:
        pass
    while True:
        # Read a line and convert it from b'xxx\r\n' to xxx
        line = ser.readline().decode('utf-8')[:-1]
        if line:  # If it isn't a blank line
               # f=open('testing.txt','w+')
            print(line)


            #print >> f.write('test.txt') 
f.close()
            #print(line)
            #with open('test.csv', 'w') as csv_file:
                  #  writer = csv.DictWriter(csv_file, fieldnames=['header1'], lineterminator='\n')
ser.close()

1 个答案:

答案 0 :(得分:0)

import sys
sys.stdout = open('file', 'w')
print 'test'

或重定向shell-output

$ python foo.py > file

重复此事: Redirect stdout to a file in Python?