简体   繁体   English

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

[英]Outputting Values of a Variable to Text File

I am pretty new to python and need to output values read in by an SPI to a text file. 我是python的新手,需要将SPI读取的值输出到文本文件。 I have a function to create the text file, and one to read the SPI but I am not sure how to get these two to interact with each other. 我有一个创建文本文件的功能,还有一个可以读取SPI的功能,但是我不确定如何使这两个文件相互交互。 I am familiar with the concept of "friends" in OOP but not how python treats separate functions in terms of how to create visibility. 我熟悉OOP中“朋友”的概念,但不熟悉python如何在创建可见性方面如何对待单独的函数。 What I need is to pass the returned value of my SPI function to the create text function so that it can be stored. 我需要将SPI函数的返回值传递给create text函数,以便可以对其进行存储。

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))

I think that what you're trying to do is the following: 我认为您要执行的操作如下:

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))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM