Python读取实时数据流示例

1、#coding:utf-8

chose = [
  ('foo',1,2),
  ('bar','hello'),
  ('foo',3,4)
]

def do_foo(x,y):
  print('foo',x,y)

def do_bar(s):
  print('bar',s)

for tag,*args in chose:
  if tag == 'foo':
    do_foo(*args)

  elif tag == 'bar':
    do_bar(*args)

line = 'nobody:*:-2:-2:Unprivileged User:/var/empty:/usr/bin/false'

uname,*fields,homedir,sh = line.split(':')
print(sh)
from collections import deque
def search(lines, pattern, history=5):
  previous_lines = deque(maxlen=history)
  for li in lines:
    if pattern in li:
      yield li, previous_lines
    previous_lines.append(li)

# Example use on a file
if __name__ == '__main__':
  with open(r'./somefiles.py') as f:
    for line, prevlines in search(f, 'python', 5):
      for pline in prevlines:
        print(pline, end='')
      print(line, end='')
      print('-' * 20)

2、import heapq

portfolio = [
{'name': 'IBM', 'shares': 100, 'price': 91.1},
{'name': 'AAPL', 'shares': 50, 'price': 543.22},
{'name': 'FB', 'shares': 200, 'price': 21.09},
{'name': 'HPQ', 'shares': 35, 'price': 31.75},
{'name': 'YHOO', 'shares': 45, 'price': 16.35},
{'name': 'ACME', 'shares': 75, 'price': 115.65}
]
cheap = heapq.nsmallest(3, portfolio, key=lambda s: s['price'])
expensive = heapq.nlargest(3, portfolio, key=lambda s: s['price'])
print(cheap)
print(expensive)

3、读取流数据源

如果数据是来自一个连续的数据源,我们需要读取连续数据,接下来

我们介绍一个适用于许多真是场景的简单解决方案,然而它并不是通用的。

操作步骤:

在本节中我们将想你演示如何读取一个实时变化的文件,并把输入打印出来。

import time
import os
import sys

if len(sys.argv) != 2:
  print('>>sys.stderr,"请输入需要读取的文件名!"')

filename = sys.argv[1]

if not os.path.isfile(filename):
  print('>>sys.stderr,"请给出需要的文件:\%s\: is not a file" % filename')

with open(filename,'r') as f:
  filesize = os.stat(filename)[6]
  f.seek(filesize)
  while True:
    where = f.tell()
    line = f.readline()
    if not line:
      time.sleep(1)
      f.seek(where)
    else:
      print(line)

以上这篇Python读取实时数据流示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持我们。

(0)

相关推荐

  • 详解python websocket获取实时数据的几种常见链接方式

    第一种, 使用create_connection链接,需要pip install websocket-client (此方法不建议使用,链接不稳定,容易断,并且连接很耗时) import time from websocket import create_connection url = 'wss://i.cg.net/wi/ws' while True: # 一直链接,直到连接上就退出循环 time.sleep(2) try: ws = create_connection(url) print

  • python中plot实现即时数据动态显示方法

    在Matlab使用Plot函数实现数据动态显示方法总结中介绍了两种实现即时数据动态显示的方法.考虑到使用python的人群日益增多,再加上本人最近想使用python动态显示即时的数据,网上方法很少,固总结于此. 示例代码1 import matplotlib.pyplot as plt import numpy as np import time from math import * plt.ion() #开启interactive mode 成功的关键函数 plt.figure(1) t =

  • python实现定时提取实时日志程序

    本文实例为大家分享了python定时提取实时日志的具体代码,供大家参考,具体内容如下 这是一个定时读取 实时日志文件的程序.目标文件是target_file. 它是应用程序实时写入的. 我要做的是,每个5秒钟,提取一次该日志文件中的内容,然后生成另一个文件,最后把这些文件都汇总. #!/usr/local/bin/python # coding:utf-8 import fileinput import time import os target_file = 'user.log' init_f

  • 实时获取Python的print输出流方法

    我的应用场景是:使用shell执行python文件,并且通过调用的返回值获取python的标准输出流. shell程序如下: cmd='python '$1' '$2' '$3' '$5' '$4 RESULT=eval $cmd echo $RESULT 之前我的写的python程序如下: # coding: utf-8 import time import json def execute(_database, _parameter): print 'sleep start' sleepTi

  • Python读取实时数据流示例

    1.#coding:utf-8 chose = [ ('foo',1,2), ('bar','hello'), ('foo',3,4) ] def do_foo(x,y): print('foo',x,y) def do_bar(s): print('bar',s) for tag,*args in chose: if tag == 'foo': do_foo(*args) elif tag == 'bar': do_bar(*args) line = 'nobody:*:-2:-2:Unpri

  • python读取dicom图像示例(SimpleITK和dicom包实现)

    1. 用SimpleITK读取dicom序列: import SimpleITK as sitk import numpy as np img_path='F:\\dataset\\pancreas\\Output\\thick\\original\\1' mask_path='F:\\dataset\\pancreas\\Output\\thick\\groundtruth\\1' reader = sitk.ImageSeriesReader() img_names = reader.Get

  • python读取csv文件示例(python操作csv)

    复制代码 代码如下: import csvfor line in open("test.csv"):name,age,birthday = line.split(",")name = name.strip(' \t\r\n');age = age.strip(' \t\r\n');birthday = birthday.strip(' \t\r\n'); print (name + '\t' + age + '\t' + birthday) csv文件 复制代码 代

  • Python 读取串口数据,动态绘图的示例

    最近工作需要把单片机读取的传感器电压数据实时在PC上通过曲线显示出来,刚好在看python, 就试着用了python 与uart端口通讯,并且通过matplotlib.pyplot 模块实时绘制图形出来. 1. 废话少说,上图 因为没有UI,运行时需要在提示符下输入串口相关参数,com端口,波特率... 代码如下: #-*- coding: utf-8 -*- # 串口测试程序 import serial import matplotlib.pyplot as plt import numpy

  • python读取目录下所有的jpg文件,并显示第一张图片的示例

    如下所示: # -*- coding: UTF-8 -*- import numpy as np import os from scipy.misc import imread, imresize import matplotlib.pyplot as plt from glob import glob # 读取目录下所有的jpg图片 def load_image(image_path, image_size): file_name=glob(image_path+"/*jpg") s

  • python读取word文档,插入mysql数据库的示例代码

    表格内容如下: 1.实现批量导入word文档,取文档标题中的数字作为编号 2.除取上面打钩的内容需要匹配出来入库入库,其他内容全部直接入库mysql # wuyanfeng # -*- coding:utf-8 -*- # 读取docx中的文本代码示例 import docx import pymysql import re import os # 创建数据库链接 conn = pymysql.connect( host='rm-bp1vu5d84dg12c6d59o.mysql.rds.ali

  • Python读取英文文件并记录每个单词出现次数后降序输出示例

    本文实例讲述了Python读取英文文件并记录每个单词出现次数后降序输出.分享给大家供大家参考,具体如下: 对文中出现的句号,逗号和感叹号做了相应的处理 sorted排序函数用法: 按照value值降序排列: sorted(dict.items(),key=lambda k:k[1],reverse=True) 按照value值升序排序: sorted(dict.items(),key=lambda k:k[1],reverse=False) 或者 sorted(dict.items(),key=

  • python 读取视频,处理后,实时计算帧数fps的方法

    实时计算每秒的帧数 cap = cv2.VideoCapture("DJI_0008.MOV") #cap = cv2.VideoCapture(0) # Define the codec and create VideoWriter object #fourcc = cv2.cv.FOURCC(*'XVID') fourcc = cv2.VideoWriter_fourcc(*'XVID') out = cv2.VideoWriter('output1.avi', fourcc, 2

  • python读取txt文件并取其某一列数据的示例

    菜鸟笔记 首先读取的txt文件如下: AAAAF110 0003E818 0003E1FC 0003E770 0003FFFC 90 AAAAF110 0003E824 0003E208 0003E76C 0003FFFC A5 AAAAF110 0003E814 0003E204 0003E760 0003FFFC 85 AAAAF110 0003E7F0 0003E208 0003E764 0003FFFC 68 AAAAF110 0003E7CC 0003E1FC 0003E758 000

  • python 读取、写入txt文件的示例

    写入文件 使用open()函数和write()函数 但是有两种写法,分别是'a'和'w' 'a' 表示写入文件 若无该文件会直接创建一个 如果存在这个文件,会接着已有的内容的后面写入 with open('D:\\test.txt','a',encoding='utf-8') as f: text = '\n奔涌吧,后浪' f.write(text) 程序运行前: 程序运行后: 'w' 表示写入文件 若无该文件会直接创建一个 如果存在这个文件,里面的内容会被后面写入的内容替换掉 with ope

随机推荐