2014-01-15 84 views
1

我想每5秒將字母X追加到列表中。我的代碼到目前爲止:每隔5秒追加

import threading 

def Seconds(): 
    threading.Timer(5.0, Seconds).start() 
    List = []  
    n = "X" 
    List.append(n) 
    print List 
Seconds() 

我想擁有一個列表,每5秒增長一次,並保存到一個TXT。每5秒記錄一次。此代碼的目的是檢查我的電池供電系統的運行時間。代碼與系統一起啓動。當電池電量不足時,我想讀出文本文件以查看代碼的執行時間,因此我的系統能夠使用電池運行多久。

+0

爲什麼不使用隊列?他們是線程安全的。 –

回答

0

運行一個獨立的過程。

def alive(): 
    with open("log.txt", "w") as output: 
     while True: 
      time.sleep(5) 
      output.write("X") 
      output.flush() # important to ensure that long periods 
         # of 'X' are not kept in buffer and lost on power down. 

p = Process(target=f, args=('bob',)) 
p.start() 

time.sleep(40) # simulate real program 
p.terminate() # eventually 
0

您的嵌入式/電池供電系統是否使用Unix?用bash腳本可以更容易實現:

#!/bin/bash 

while true 
do 
    cat /proc/uptime > log.txt 
    sleep 5 
done 

然後,您將獲得確切的正常運行時間。請注意,在測量這些數據時,您可能會因無法使處理器進入低功耗狀態並導致額外的磁盤寫入而意外使用更多能源。

編輯,粗糙的Python版本不依賴於OS

#!/bin/python 
import time 

starttime = time.time() 

while True: 
    with open('log.txt', 'w') as log: 
     print >> log, time.time() - starttime 
    time.sleep(5) 

注意的時候會被時間運行此腳本之前所花費的金額被關閉。

+0

OP的用例是收集系統的運行時間,這符合法案。不需要使用大錘擊釘。 – Tim

+0

也許你是對的。但是在這個問題中沒有關於操作系統的信息(不管它是否是** nix **)。 – sergzach