简体   繁体   English

是否可以在python中的终端中创建一个日志文件?

[英]Is it possible to create a log file in the terminal in python?

I have a Python program that takes about three voltage readings per second. 我有一个Python程序,每秒需要大约三个电压读数。 I normally run it from the Linux desktop Lxterminal. 我通常从Linux桌面Lxterminal运行它。 Then later the voltages vs time are used in Pylab to create a plot. 然后在Pylab中使用电压与时间来创建绘图。 However as it takes voltage readings it sometimes will pause, which creates gaps in the data, which can ruin the test. 然而,由于它需要电压读数,它有时会暂停,这会在数据中产生间隙,这可能会破坏测试。 These gaps last from 1 to 6 seconds. 这些间隙持续1到6秒。 I noticed the pauses are caused by my program's 'print >> logfile, time(), (volts)' script. 我注意到暂停是由程序的'print >> logfile,time(),(volts)'脚本引起的。 But if I remove the logfile script and run it from the command prompt (aka "the terminal", "the console", "the shell") these pauses are not there. 但是,如果我删除日志文件脚本并从命令提示符(也称为“终端”,“控制台”,“shell”)运行它,这些暂停不存在。 When I run program from the command prompt it prints out a long series of voltages that show up on the monitor, but there is no log file to use to create a plot. 当我从命令提示符运行程序时,它打印出显示在监视器上的一系列电压,但是没有用于创建绘图的日志文件。 My question is, is there a way to store these voltages in the terminal shell and then use these nice no-gaps voltages later on in Pylab? 我的问题是,有没有办法将这些电压存储在终端外壳中,然后在Pylab中使用这些漂亮的无间隙电压? I tried: 我试过了:

 list = time(), volts

But I don't know what to do next or if I'm even heading in the right direction. 但我不知道下一步该做什么,或者我是否朝着正确的方向前进。 Here is my program. 这是我的计划。

import time, sys, signal, math    
from Adafruit_ADS1x15 import ADS1x15    
from time import time, sleep    
def signal_handler(signal, frame):    
    sys.exit(0)    
signal.signal(signal.SIGINT, signal_handler)    
ADS1115 = 0x01    
adc = ADS1x15(ic=ADS1115)    

while True:    
   voltsdiff = adc.readADCDifferential01(4096, 8)    
   logfile = open('logfile.txt', 'a')    
   print >> logfile, time(), voltsdiff    
   logfile.close()    
   sleep(0.25)  

Take a look at the logging module 看一下logging模块

import logging

logging.basicConfig(filename=LOG_FILENAME, level=logging.DEBUG)

logging.debug(yourdataToSaveInFile)

No need to open and close your file every loop iteration. 无需在每次循环迭代时打开和关闭文件。

with open('logfile.txt', 'a') as f:
    while True:    
       voltsdiff = adc.readADCDifferential01(4096, 8)    
       print >> f, time(), voltsdiff    
       sleep(0.25)

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

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