同时写入多个文件

时间:2016-04-14 21:24:37

标签: python file microcontroller sensor beagleboneblack

我正在开发一个项目,涉及使用Beaglebone从多个传感器读取,然后将数据传递到文本文件中。我正在监视六个不同的肌肉,所以我有文件对应每个。

现在,有6个传感器进入Beaglebone Black的ADC引脚,我的代码指示Beaglebone为每个引脚创建1个独立的文件。每当我运行下面的代码时,我只获得一个文件(第一个函数运行)。以前我没有包含“while True:”语句,这些语句导致1-2个读数和6个文件被创建。我添加了“while True:”来连续记录传感器的数据,因为我认为这是我每个文件中没有超过2个点的原因。

我的问题是:是否可以同时写入多个文件?我也可以将所有这些数据写入同一个文件,但我很想知道是什么让这段代码无法正常运行(6个文件。)

        #File save for left hamstring
def LeftHamAcquisition():
        HamLData = open('HamLeft' + '.txt', 'a+')
        file_name = os.path.join(/relevant file path/)
        while True:
                EMGhamL = ADC.read_raw('AIN1')
                HamLData.write(str(elapsed_milliseconds))
                HamLData.write('\t')
                HamLData.write(str(EMGhamL))
                HamLData.write('\n')

        #File save for right hams
def RighHamAcquisition():
        HamRData = open('HamRight' + '.txt', 'a+')
        file_name2 = os.path.join(/relevant file path/)
        while True:
                EMGhamR = ADC.read_raw('AIN2')
                HamRData.write(str(elapsed_milliseconds))
                HamRData.write('\t')
                HamRData.write(str(EMGhamR))
                HamRData.write('\n')


        #file save for left quad
def LeftQuadAcquisition():        
        QuadLData = open('QuadLeft' + '.txt', 'a+')
        file_name3 = os.path.join(/relevant file path/)
        while True:
                EMGquadL = ADC.read_raw('AIN3')
                QuadLData.write(str(elapsed_milliseconds))
                QuadLData.write('\t')
                QuadLData.write(str(EMGquadL))
                QuadLData.write('\n')

        #file save for right quad
def RightQuadAcquisition():
        QuadRData = open('QuadRight' + '.txt', 'a+')
        file_name4 = os.path.join(/relevant file path/)
        while True:
                EMGquadR = ADC.read_raw('AIN4')
                QuadRData.write(str(elapsed_milliseconds))
                QuadRData.write('\t')
                QuadRData.write(str(EMGquadR))
                QuadRData.write('\n')

        #file save for left vast
def LeftVastAcquisition():
        VastLData = open('VastLeft' + '.txt', 'a+')
        file_name5 = os.path.join(/relevant file path/)
        while True:
                EMGVastL = ADC.read_raw('AIN5')
                VastLData.write(str(elapsed_milliseconds))
                VastLData.write('\t')
                VastLData.write(str(EMGVastL))
                VastLData.write('\n')

        #file save for right vast
def RightVastAcquisition():
        VastRData = open('VastRight' + '.txt', 'a+')
        file_name6 = os.path.join(/relevant file path/)
        while True:
                EMGVastR = ADC.read_raw('AIN6')
                VastRData.write(str(elapsed_milliseconds))
                VastRData.write('\t')
                VastRData.write(str(EMGVastR))
                VastRData.write('\n')

#The Program
print "Press ctrl-C to end acquisition"

LeftHamAcquisition()
RighHamAcquisition()
LeftVastAcquisition()
RightVastAcquisition()
LeftQuadAcquisition()
RightQuadAcquisition()

try:
    pass
except KeyboardInterrupt:      
    raise data.close()

1 个答案:

答案 0 :(得分:0)

你的函数调用中有无限循环,所以它们永远不会返回。一个文件是由LeftHamAcquisition创建的,但由于它从未返回,因此没有其他函数被执行过。您需要使用类似multiprocessing module的内容来使它们并行运行。特别是,我建议multiprocessing poolsapply_async函数:

import multiprocessing
import Queue
import time

# one global constant: the poison pill
# this could really be whatever you want - my string choice is arbitrary
STOP = "stop"

# change the signature of your function to accept a queue for the main 
# process to pass a poison pill
def LeftHamAcquisition(kill_queue):
    f_name = 'HamLeft.txt'

    # you aren't doing anything with "file_name" - should it be removed?
    # file_name = os.path.join(/relevant file path/)

    # use file context managers:
    with open(fname, 'a+') as HamLData:
        while True:

            # in the infinite loop, we add a check for the poison pill
            try:
                val = kill_queue.get(block=False)
                if val = STOP:
                    return # leave if the poison pill was sent
            except Queue.Empty:
                pass # ignore empty queue

            EMGhamL = ADC.read_raw('AIN1')
            HamLData.write(str(elapsed_milliseconds))
            HamLData.write('\t')
            HamLData.write(str(EMGhamL))
            HamLData.write('\n')

# ... the rest of your functions ...

#The Program
print "Press ctrl-C to end acquisition"

# a list of your functions
f_list = [
    LeftHamAcquisition,
    RighHamAcquisition,
    LeftVastAcquisition,
    RightVastAcquisition,
    LeftQuadAcquisition,
    RightQuadAcquisition,
]

pool = multiprocessing.Pool()    #c reate the worker pool
kill_queue = multiprocessing.Queue() # create the queue to pass poison pills

for f in f_list:
    # kick off the functions, passing them the poison pill queue
    pool.apply_async(f, args=(kill_queue))     
try:
    # put the main process to sleep while the workers do their thing
    while True:
        time.sleep(60)

except KeyboardInterrupt:      

    # close the workers nicely - put one poison pill on the queue for each
    for f in f_list:
        q.put(STOP)
    pool.close()
    pool.join()
    raise data.close()

此外,没有理由拥有这么多功能。他们都做同样的事情,只是使用不同的字符串和变量名称。您应该将它们重构为一个可以将参数传递给的函数:

def acquisition(kill_queue, f_name, ain):

    with open(fname, 'a+') as f:
        while True:

            try:
                val = kill_queue.get(block=False)
                if val = STOP:
                    return
            except Queue.Empty:
                pass

            an_val = ADC.read_raw(ain)

            # where does "elapsed_milliseconds" come from? it's undefined
            # in your example code
            f.write("{}\t{}\n".format(elapsed_milliseconds, an_val))

使用此函数,您可以重复使用此函数,使用不同的参数(这是函数的整个点)重复调用它,而不是在我的多处理示例中提供单个函数的列表。