将变量的值输出到文本文件

时间:2014-06-02 22:38:05

标签: python spi

我是python的新手,需要将SPI读入的值输出到文本文件。我有一个函数来创建文本文件,一个用于读取SPI,但我不知道如何让这两个文件互相交互。我熟悉OOP中“朋友”的概念,但不熟悉python如何在如何创建可见性方面处理单独的函数。我需要的是将我的SPI函数的返回值传递给创建文本函数,以便可以存储它。

def timeStamp(fname, fmt = '%Y%m%d--%H%M%S_{fname}'):                       
    return datetime.datetime.now().strftime(fmt).format(fname = fname)

with open (timeStamp('SPI_Inputs'), 'w') as output:     
        output.write('this needs to be adc output')

def readadc(adcnum):
    if adcnum > 7 or adcnum < 0:
        return -1
    r = spi.xfer2([1,8 + adcnum << 4,0])
    adcout = ((r[1] & 3) << 8) + r[2]
    return adcout   #this needs to be put into text file

while True:
    ADC_Val = int(round(readadc(0)/10.24))
    print "Input = ", ADC_Val
    count = count +1
    time.sleep (0.2)

    timeStamp(readadc))

1 个答案:

答案 0 :(得分:0)

我认为您尝试做的事情如下:

def timeStamp(fname, fmt = '%Y%m%d--%H%M%S_{fname}'):                       
    return datetime.datetime.now().strftime(fmt).format(fname = fname)

def write_to_file(str):
    with open (timeStamp('SPI_Inputs'), 'w') as output:     
        output.write(str)

def readadc(adcnum):
    if adcnum > 7 or adcnum < 0:
        return -1
    r = spi.xfer2([1,8 + adcnum << 4,0])
    adcout = ((r[1] & 3) << 8) + r[2]
    return adcout   #this needs to be put into text file

while True:
    ADC_Val = int(round(readadc(0)/10.24))
    write_to_file(ADC_Val)
    print "Input = ", ADC_Val
    time.sleep (0.2)
    print timeStamp(readadc))