Python读取实时数据流示例

yipeiwu_com6年前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读取实时数据流示例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

实例解析Python设计模式编程之桥接模式的运用

实例解析Python设计模式编程之桥接模式的运用

我们先来看一个例子: #encoding=utf-8 # #by panda #桥接模式 def printInfo(info): print unicode(i...

使用Python编写提取日志中的中文的脚本的方法

使用Python编写提取日志中的中文的脚本的方法

由于工作需要在一大堆日志里面提取相应的一些固定字符,如果单纯靠手工取提取,数据量大,劳心劳力,于是自然而然想到了用Python做一个对应的提取工具,代替手工提取的繁杂,涉及中文字符,正则...

Python异常学习笔记

异常(exceptions)是Python中一种非常重要的类型,它和语法错误不同,是在程序运行期间引发的错误。Python中内置了很多异常,如IOError,NameError,Keyb...

对python中的xlsxwriter库简单分析

一、xlsxwriter 基本用法,创建 xlsx 文件并添加数据 官方文档:http://xlsxwriter.readthedocs.org/ xlsxwriter 可以操作 xls...

使用python实现简单五子棋游戏

使用python实现简单五子棋游戏

用python实现五子棋简单人机模式的练习过程,供大家参考,具体内容如下 第一次写博客,我尽力把它写好。 最近在初学python,今天就用自己的一些粗浅理解,来记录一下这几天的pytho...