SlideShare uma empresa Scribd logo
1 de 26
Maxym Kharchenko & m@ team
Writing efficient Python code with
pipelines and generators
Agenda
Python is all about streaming (a.k.a. iteration)
Streaming in Python
# Lists
db_list = ['db1', 'db2', 'db3']
for db in db_list:
print db
# Dictionaries
host_cpu = {'avg': 2.34, 'p99': 98.78, 'min': 0.01}
for stat in host_cpu:
print "%s = %s" % (stat, host_cpu[stat])
# Files, strings
file = open("/etc/oratab")
for line in file:
for word in line.split(" "):
print word
# Whatever is coming out of get_things()
for thing in get_things():
print thing
Quick example: Reading records from a file
def print_databases():
""" Read /etc/oratab and print database names """
file = open("/etc/oratab", 'r')
while True:
line = file.readline() # Get next line
# Check for empty lines
if len(line) == 0 and not line.endswith('n'):
break
# Parsing oratab line into components
db_line = line.strip()
db_info_array = db_line.split(':')
db_name = db_info_array[0]
print db_name
file.close()
Reading records from a file: with “streaming”
def print_databases():
""" Read /etc/oratab and print database names """
with open("/etc/oratab") as file:
for line in file:
print line.strip().split(':')[0]
Style matters!
Ok, let’s do something useful with streaming
 We have a bunch of ORACLE listener logs
 Let’s parse them for “client IPs”
21-AUG-2015 21:29:56 *
(CONNECT_DATA=(SID=orcl)(CID=(PROGRAM=)(HOST=_
_jdbc__)(USER=))) *
(ADDRESS=(PROTOCOL=tcp)(HOST=10.107.137.91)(PO
RT=43105)) * establish * orcl * 0
 And find where the clients are coming from
First attempt at listener log parser
def parse_listener_log(log_name):
""" Parse listener log and return clients
"""
client_hosts = []
with open(log_name) as listener_log:
for line in listener_log:
host_match = <regex magic>
if host_match:
host = <regex magic>
client_hosts.append(host)
return client_hosts
First attempt at listener log parser
def parse_listener_log(log_name):
""" Parse listener log and return clients
"""
client_hosts = []
with open(log_name) as listener_log:
for line in listener_log:
host_match = <regex magic>
if host_match:
host = <regex magic>
client_hosts.append(host)
return client_hosts
MEMORY
WASTE!
Stores all
results until
return
BLOCKING!
Does NOT
return until
the entire log
is processed
Generators for efficiency
def parse_listener_log(log_name):
""" Parse listener log and return clients
"""
client_hosts = []
with open(log_name) as listener_log:
for line in listener_log:
host_match = <regex magic>
if host_match:
host = <regex magic>
client_hosts.append(host)
return client_hosts
Generators for efficiency
def parse_listener_log(log_name):
""" Parse listener log and return clients
"""
client_hosts = []
with open(log_name) as listener_log:
for line in listener_log:
host_match = <regex magic>
if host_match:
host = <regex magic>
client_hosts.append(host)
return client_hosts
Generators for efficiency
def parse_listener_log(log_name):
""" Parse listener log and return clients
"""
with open(log_name) as listener_log:
for line in listener_log:
host_match = <regex magic>
if host_match:
host = <regex magic>
yield hostAdd this !
Generators in a nutshell
def test_generator():
""" Test generator """
print "ENTER()"
for i in range(5):
print "yield i=%d" % i
yield i
print "EXIT()"
# MAIN
for i in test_generator():
print "RET=%d" % i
ENTER()
yield i=0
RET=0
yield i=1
RET=1
yield i=2
RET=2
yield i=3
RET=3
yield i=4
RET=4
EXIT()
Nongenerators in a nutshell
def test_nongenerator():
""" Test no generator """
result = []
print "ENTER()"
for i in range(5):
print "add i=%d" % i
result.append(i)
print "EXIT()"
return result
# MAIN
for i in test_nongenerator():
print "RET=%d" % i
ENTER()
add i=0
add i=1
add i=2
add i=3
add i=4
EXIT()
RET=0
RET=1
RET=2
RET=3
RET=4
Generators to Pipelines
Generator
(extractor)
1 second
per record
100,000
1st:
1 second
100,000
Generator
(filter: 1/2)
2 seconds
per record
Generator
(mapper)
5 seconds
per record
50,000
1st:
5 seconds
50,000
1st:
10 seconds
Generator pipelining in Python
file_handles = open_files(LISTENER_LOGS)
log_lines = extract_lines(file_handles)
client_hosts = extract_client_ips(log_lines)
for host in client_hosts:
print host
Open
files
Extract
lines
Extract
IPs
File
names
File
handles
File
lines
Client
IPs
Generators for simplicity
def open_files(file_names):
""" GENERATOR: file name -> file handle """
for file in file_names:
yield open(file)
Generators for simplicity
def extract_lines(file_handles):
""" GENERATOR: File handles -> file lines
Similar to UNIX: cat file1, file2, …
"""
for file in file_handles:
for line in file:
yield line
Generators for simplicity
def extract_client_ips(lines):
""" GENERATOR: Extract client host
"""
host_regex = re.compile('(HOST=(S+))(PORT=')
for line in lines:
line_match = host_regex.search(line)
if line_match:
yield line_match.groups(0)[0]
Developer’s bliss:
simple input, simple output, trivial function body
Then, pipeline the results
But, really …
Open
files
Extract
lines
IP ->
host
name
File
names
File
handles
File
lines
Client
hosts
Locate
files
Filter
db=orcl
Filter
proto=
TCP
db=orcl
lines
db=orcl
lines
db=orcl
&
prot=TCP
Extract
clients
Client
IPs
Client
hosts
Db
writer
Client
hosts
Text
writer
Why generators ?
 Simple functions that are easy to write and understand
 Non blocking operations:
 TOTAL execution time: faster
 FIRST RESULTS: much faster
 Efficient use of memory
 Potential for parallelization and ASYNC processing
Special thanks to David Beazley …
 For this: http://www.dabeaz.com/generators-uk/GeneratorsUK.pdf
Thank you!

Mais conteúdo relacionado

Mais procurados

Impala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for HadoopImpala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for HadoopAll Things Open
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for BeginnersArie Bregman
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueGleicon Moraes
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKYoungHeon (Roy) Kim
 
Parse, scale to millions
Parse, scale to millionsParse, scale to millions
Parse, scale to millionsFlorent Vilmart
 
How to admin
How to adminHow to admin
How to adminyalegko
 
Value protocols and codables
Value protocols and codablesValue protocols and codables
Value protocols and codablesFlorent Vilmart
 
CouchDB Day NYC 2017: Introduction to CouchDB 2.0
CouchDB Day NYC 2017: Introduction to CouchDB 2.0CouchDB Day NYC 2017: Introduction to CouchDB 2.0
CouchDB Day NYC 2017: Introduction to CouchDB 2.0IBM Cloud Data Services
 
Overloading Perl OPs using XS
Overloading Perl OPs using XSOverloading Perl OPs using XS
Overloading Perl OPs using XSℕicolas ℝ.
 
Perl Memory Use - LPW2013
Perl Memory Use - LPW2013Perl Memory Use - LPW2013
Perl Memory Use - LPW2013Tim Bunce
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2Leandro Lima
 

Mais procurados (20)

Impala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for HadoopImpala: A Modern, Open-Source SQL Engine for Hadoop
Impala: A Modern, Open-Source SQL Engine for Hadoop
 
working with files
working with filesworking with files
working with files
 
Using Logstash, elasticsearch & kibana
Using Logstash, elasticsearch & kibanaUsing Logstash, elasticsearch & kibana
Using Logstash, elasticsearch & kibana
 
Ansible for Beginners
Ansible for BeginnersAnsible for Beginners
Ansible for Beginners
 
CouchDB Day NYC 2017: Full Text Search
CouchDB Day NYC 2017: Full Text SearchCouchDB Day NYC 2017: Full Text Search
CouchDB Day NYC 2017: Full Text Search
 
RestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message QueueRestMQ - HTTP/Redis based Message Queue
RestMQ - HTTP/Redis based Message Queue
 
MySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELKMySQL Slow Query log Monitoring using Beats & ELK
MySQL Slow Query log Monitoring using Beats & ELK
 
Parse, scale to millions
Parse, scale to millionsParse, scale to millions
Parse, scale to millions
 
Database Homework Help
Database Homework HelpDatabase Homework Help
Database Homework Help
 
serverstats
serverstatsserverstats
serverstats
 
How to admin
How to adminHow to admin
How to admin
 
Value protocols and codables
Value protocols and codablesValue protocols and codables
Value protocols and codables
 
CouchDB Day NYC 2017: Introduction to CouchDB 2.0
CouchDB Day NYC 2017: Introduction to CouchDB 2.0CouchDB Day NYC 2017: Introduction to CouchDB 2.0
CouchDB Day NYC 2017: Introduction to CouchDB 2.0
 
Nginx-lua
Nginx-luaNginx-lua
Nginx-lua
 
CouchDB Day NYC 2017: MapReduce Views
CouchDB Day NYC 2017: MapReduce ViewsCouchDB Day NYC 2017: MapReduce Views
CouchDB Day NYC 2017: MapReduce Views
 
Overloading Perl OPs using XS
Overloading Perl OPs using XSOverloading Perl OPs using XS
Overloading Perl OPs using XS
 
Perl Memory Use - LPW2013
Perl Memory Use - LPW2013Perl Memory Use - LPW2013
Perl Memory Use - LPW2013
 
CouchDB Day NYC 2017: Replication
CouchDB Day NYC 2017: ReplicationCouchDB Day NYC 2017: Replication
CouchDB Day NYC 2017: Replication
 
Lies, Damn Lies, and Benchmarks
Lies, Damn Lies, and BenchmarksLies, Damn Lies, and Benchmarks
Lies, Damn Lies, and Benchmarks
 
Workshop on command line tools - day 2
Workshop on command line tools - day 2Workshop on command line tools - day 2
Workshop on command line tools - day 2
 

Semelhante a Commit2015 kharchenko - python generators - ext

Fluentd unified logging layer
Fluentd   unified logging layerFluentd   unified logging layer
Fluentd unified logging layerKiyoto Tamura
 
Make Sure Your Applications Crash
Make Sure Your  Applications CrashMake Sure Your  Applications Crash
Make Sure Your Applications CrashMoshe Zadka
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingMuthu Vinayagam
 
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docxLab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docxDIPESH30
 
Streaming Way to Webscale: How We Scale Bitly via Streaming
Streaming Way to Webscale: How We Scale Bitly via StreamingStreaming Way to Webscale: How We Scale Bitly via Streaming
Streaming Way to Webscale: How We Scale Bitly via StreamingAll Things Open
 
headerfilesinc-181121134545 (1).pdf
headerfilesinc-181121134545 (1).pdfheaderfilesinc-181121134545 (1).pdf
headerfilesinc-181121134545 (1).pdfjazzcashlimit
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a bossgsterndale
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+ConFoo
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQLPeter Eisentraut
 
Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout source{d}
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parserkamaelian
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in pythonKarin Lagesen
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbJuan Maiz
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Puppet
 
Replacing "exec" with a type and provider
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and providerDominic Cleal
 

Semelhante a Commit2015 kharchenko - python generators - ext (20)

Python basic
Python basicPython basic
Python basic
 
Fluentd unified logging layer
Fluentd   unified logging layerFluentd   unified logging layer
Fluentd unified logging layer
 
Make Sure Your Applications Crash
Make Sure Your  Applications CrashMake Sure Your  Applications Crash
Make Sure Your Applications Crash
 
GE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python ProgrammingGE8151 Problem Solving and Python Programming
GE8151 Problem Solving and Python Programming
 
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docxLab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
Lab01Filesbuild.bat@echo offclsset DRIVE_LETTER=1.docx
 
Assignment6
Assignment6Assignment6
Assignment6
 
Tres Gemas De Ruby
Tres Gemas De RubyTres Gemas De Ruby
Tres Gemas De Ruby
 
Header files in c
Header files in cHeader files in c
Header files in c
 
Streaming Way to Webscale: How We Scale Bitly via Streaming
Streaming Way to Webscale: How We Scale Bitly via StreamingStreaming Way to Webscale: How We Scale Bitly via Streaming
Streaming Way to Webscale: How We Scale Bitly via Streaming
 
headerfilesinc-181121134545 (1).pdf
headerfilesinc-181121134545 (1).pdfheaderfilesinc-181121134545 (1).pdf
headerfilesinc-181121134545 (1).pdf
 
Refactor like a boss
Refactor like a bossRefactor like a boss
Refactor like a boss
 
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+Marrow: A Meta-Framework for Python 2.6+ and 3.1+
Marrow: A Meta-Framework for Python 2.6+ and 3.1+
 
Programming with Python and PostgreSQL
Programming with Python and PostgreSQLProgramming with Python and PostgreSQL
Programming with Python and PostgreSQL
 
Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout Introduction to source{d} Engine and source{d} Lookout
Introduction to source{d} Engine and source{d} Lookout
 
DataMapper
DataMapperDataMapper
DataMapper
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parser
 
Functions and modules in python
Functions and modules in pythonFunctions and modules in python
Functions and modules in python
 
Background Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRbBackground Jobs - Com BackgrounDRb
Background Jobs - Com BackgrounDRb
 
Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...Replacing "exec" with a type and provider: Return manifests to a declarative ...
Replacing "exec" with a type and provider: Return manifests to a declarative ...
 
Replacing "exec" with a type and provider
Replacing "exec" with a type and providerReplacing "exec" with a type and provider
Replacing "exec" with a type and provider
 

Último

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationBradBedford3
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecturerahul_net
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxAndreas Kunz
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalLionel Briand
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesVictoriaMetrics
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsChristian Birchler
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...OnePlan Solutions
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLionel Briand
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Anthony Dahanne
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldRoberto Pérez Alcolea
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtimeandrehoraa
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptxVinzoCenzo
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Cizo Technology Services
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingShane Coughlan
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsJean Silva
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolsosttopstonverter
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorTier1 app
 

Último (20)

How to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion ApplicationHow to submit a standout Adobe Champion Application
How to submit a standout Adobe Champion Application
 
Understanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM ArchitectureUnderstanding Flamingo - DeepMind's VLM Architecture
Understanding Flamingo - DeepMind's VLM Architecture
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptxUI5ers live - Custom Controls wrapping 3rd-party libs.pptx
UI5ers live - Custom Controls wrapping 3rd-party libs.pptx
 
Precise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive GoalPrecise and Complete Requirements? An Elusive Goal
Precise and Complete Requirements? An Elusive Goal
 
What’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 UpdatesWhat’s New in VictoriaMetrics: Q1 2024 Updates
What’s New in VictoriaMetrics: Q1 2024 Updates
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving CarsSensoDat: Simulation-based Sensor Dataset of Self-driving Cars
SensoDat: Simulation-based Sensor Dataset of Self-driving Cars
 
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
Tech Tuesday Slides - Introduction to Project Management with OnePlan's Work ...
 
Large Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and RepairLarge Language Models for Test Case Evolution and Repair
Large Language Models for Test Case Evolution and Repair
 
Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024Not a Kubernetes fan? The state of PaaS in 2024
Not a Kubernetes fan? The state of PaaS in 2024
 
Keeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository worldKeeping your build tool updated in a multi repository world
Keeping your build tool updated in a multi repository world
 
SpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at RuntimeSpotFlow: Tracking Method Calls and States at Runtime
SpotFlow: Tracking Method Calls and States at Runtime
 
Osi security architecture in network.pptx
Osi security architecture in network.pptxOsi security architecture in network.pptx
Osi security architecture in network.pptx
 
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
Global Identity Enrolment and Verification Pro Solution - Cizo Technology Ser...
 
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full RecordingOpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
OpenChain Education Work Group Monthly Meeting - 2024-04-10 - Full Recording
 
Strategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero resultsStrategies for using alternative queries to mitigate zero results
Strategies for using alternative queries to mitigate zero results
 
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News UpdateVictoriaMetrics Q1 Meet Up '24 - Community & News Update
VictoriaMetrics Q1 Meet Up '24 - Community & News Update
 
eSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration toolseSoftTools IMAP Backup Software and migration tools
eSoftTools IMAP Backup Software and migration tools
 
Effectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryErrorEffectively Troubleshoot 9 Types of OutOfMemoryError
Effectively Troubleshoot 9 Types of OutOfMemoryError
 

Commit2015 kharchenko - python generators - ext

  • 1. Maxym Kharchenko & m@ team Writing efficient Python code with pipelines and generators
  • 3. Python is all about streaming (a.k.a. iteration)
  • 4. Streaming in Python # Lists db_list = ['db1', 'db2', 'db3'] for db in db_list: print db # Dictionaries host_cpu = {'avg': 2.34, 'p99': 98.78, 'min': 0.01} for stat in host_cpu: print "%s = %s" % (stat, host_cpu[stat]) # Files, strings file = open("/etc/oratab") for line in file: for word in line.split(" "): print word # Whatever is coming out of get_things() for thing in get_things(): print thing
  • 5. Quick example: Reading records from a file def print_databases(): """ Read /etc/oratab and print database names """ file = open("/etc/oratab", 'r') while True: line = file.readline() # Get next line # Check for empty lines if len(line) == 0 and not line.endswith('n'): break # Parsing oratab line into components db_line = line.strip() db_info_array = db_line.split(':') db_name = db_info_array[0] print db_name file.close()
  • 6. Reading records from a file: with “streaming” def print_databases(): """ Read /etc/oratab and print database names """ with open("/etc/oratab") as file: for line in file: print line.strip().split(':')[0]
  • 8. Ok, let’s do something useful with streaming  We have a bunch of ORACLE listener logs  Let’s parse them for “client IPs” 21-AUG-2015 21:29:56 * (CONNECT_DATA=(SID=orcl)(CID=(PROGRAM=)(HOST=_ _jdbc__)(USER=))) * (ADDRESS=(PROTOCOL=tcp)(HOST=10.107.137.91)(PO RT=43105)) * establish * orcl * 0  And find where the clients are coming from
  • 9. First attempt at listener log parser def parse_listener_log(log_name): """ Parse listener log and return clients """ client_hosts = [] with open(log_name) as listener_log: for line in listener_log: host_match = <regex magic> if host_match: host = <regex magic> client_hosts.append(host) return client_hosts
  • 10. First attempt at listener log parser def parse_listener_log(log_name): """ Parse listener log and return clients """ client_hosts = [] with open(log_name) as listener_log: for line in listener_log: host_match = <regex magic> if host_match: host = <regex magic> client_hosts.append(host) return client_hosts MEMORY WASTE! Stores all results until return BLOCKING! Does NOT return until the entire log is processed
  • 11. Generators for efficiency def parse_listener_log(log_name): """ Parse listener log and return clients """ client_hosts = [] with open(log_name) as listener_log: for line in listener_log: host_match = <regex magic> if host_match: host = <regex magic> client_hosts.append(host) return client_hosts
  • 12. Generators for efficiency def parse_listener_log(log_name): """ Parse listener log and return clients """ client_hosts = [] with open(log_name) as listener_log: for line in listener_log: host_match = <regex magic> if host_match: host = <regex magic> client_hosts.append(host) return client_hosts
  • 13. Generators for efficiency def parse_listener_log(log_name): """ Parse listener log and return clients """ with open(log_name) as listener_log: for line in listener_log: host_match = <regex magic> if host_match: host = <regex magic> yield hostAdd this !
  • 14. Generators in a nutshell def test_generator(): """ Test generator """ print "ENTER()" for i in range(5): print "yield i=%d" % i yield i print "EXIT()" # MAIN for i in test_generator(): print "RET=%d" % i ENTER() yield i=0 RET=0 yield i=1 RET=1 yield i=2 RET=2 yield i=3 RET=3 yield i=4 RET=4 EXIT()
  • 15. Nongenerators in a nutshell def test_nongenerator(): """ Test no generator """ result = [] print "ENTER()" for i in range(5): print "add i=%d" % i result.append(i) print "EXIT()" return result # MAIN for i in test_nongenerator(): print "RET=%d" % i ENTER() add i=0 add i=1 add i=2 add i=3 add i=4 EXIT() RET=0 RET=1 RET=2 RET=3 RET=4
  • 16. Generators to Pipelines Generator (extractor) 1 second per record 100,000 1st: 1 second 100,000 Generator (filter: 1/2) 2 seconds per record Generator (mapper) 5 seconds per record 50,000 1st: 5 seconds 50,000 1st: 10 seconds
  • 17. Generator pipelining in Python file_handles = open_files(LISTENER_LOGS) log_lines = extract_lines(file_handles) client_hosts = extract_client_ips(log_lines) for host in client_hosts: print host Open files Extract lines Extract IPs File names File handles File lines Client IPs
  • 18. Generators for simplicity def open_files(file_names): """ GENERATOR: file name -> file handle """ for file in file_names: yield open(file)
  • 19. Generators for simplicity def extract_lines(file_handles): """ GENERATOR: File handles -> file lines Similar to UNIX: cat file1, file2, … """ for file in file_handles: for line in file: yield line
  • 20. Generators for simplicity def extract_client_ips(lines): """ GENERATOR: Extract client host """ host_regex = re.compile('(HOST=(S+))(PORT=') for line in lines: line_match = host_regex.search(line) if line_match: yield line_match.groups(0)[0]
  • 21. Developer’s bliss: simple input, simple output, trivial function body
  • 23. But, really … Open files Extract lines IP -> host name File names File handles File lines Client hosts Locate files Filter db=orcl Filter proto= TCP db=orcl lines db=orcl lines db=orcl & prot=TCP Extract clients Client IPs Client hosts Db writer Client hosts Text writer
  • 24. Why generators ?  Simple functions that are easy to write and understand  Non blocking operations:  TOTAL execution time: faster  FIRST RESULTS: much faster  Efficient use of memory  Potential for parallelization and ASYNC processing
  • 25. Special thanks to David Beazley …  For this: http://www.dabeaz.com/generators-uk/GeneratorsUK.pdf

Notas do Editor

  1. Doing things “pythonian” way
  2. “All” results vs 1st results
  3. The best “generator” presentation that I’ve seen