SlideShare a Scribd company logo
THE PYTHON STD LIB BY EXAMPLE
– APPLICATION BUILDING BLOCKS
John
Saturday, December 21, 2013
Brief introduction
• This lesson covers some of the more frequently
reused building blocks that solve problems
common to many applications
• Command-line argument parsing: module
getopt,optparse,argparse.
• Interactive programs: readline, cmd,
shlex,fileinput
• Manage application configuration: ConfigParser
• Manage log file: logging
• Others: atexit, sched etc
Module getopt – option parsing
• The getopt() take 3 arguments:
1. The sequeence of arguments to be parsed.
Usually it is sys.argv[1:]
2. Single-character option, following a colon(:)
mean it require an argument. E.g. ab:c:, it mean
a is -a simple flag, while –b and –c require an
argument.
3. It is optional. If used, it is a list of long-style
option names. Having suffix “=“ means ruquire
an argument. E.g [‘noarg’,’witharg=‘]
Quick example 1
# file test.py
import getopt
import sys
opts,args = getopt.getopt(sys.argv[1:],’ab:c:’)
for opt in opts:
print opt
•Then run command line “python test.py –a –b valb –c valc”, the output
should be
('-a', '')
('-b', 'val')
('-c', 'val')
quick example 2
# file test.py
import getopt
import sys
opts,args = getopt.getopt(sys.argv[1:],’’,[‘opta’,’optb=‘,’optc=‘])
for opt in opts:
print opt
•run command line “python test.py --opta --optb val --optc val”
('--opta', '')
('--optb', 'val')
('--optc', 'val')
Module optparse
• it is a modern alternative for module getopt
Quick example

Example 2:
More options in add_option
method
• option dest: the attribute name
• option default: the default value. also can be set in
set_defaults method.
• option type: convert the argument string to specific type,
e.g. int, float,string
• option choices: validation use a list of candidate strings. e.g.
choices=[‘a’,’b’,’c’] . the valid value should be ‘a’, or ‘b’ or ‘c’
• option help: help message
• option action: store, store_const,store_true,append,acount
Module argparse
• argparse added to python 2.7 as a
replacement of optparse.
• Change the OptionParser by ArgumentParser,
and add_option by add_argument in
previous example.
More Options of ArgumentParser
• add help automatically:

parser = argparse.ArgumentParser(add_help=True)

• version control: version=‘1.0’ (-v or --version
will show the version number)
More options of add_argument
method
• All options in optparse.add_option method.
• option nargs: number of expected
arguments. (? mean 0 or 1 arguments, *
means 0 or all, + means 1 or all).
example
parser.add_argument(‘-c’,nargs=3)
we need write command line “perl -c 1 2 3”
Module getpass: handle passowrd
prompts securely
• print a promt and then read input from the user.

• We can change the prompt:
getpass(prompt=‘what is your favorite color?’)
MODULE CMD:
BUILD COMMAND
LINE PROCESSORS
brief introduction
• the Cmd class is used as base class for
interactive shells and other command
interpreters.
• It can provide interactive prompt, commandline editing, and command completion.
quick example

• method do_greet() connect with command “greet”
• method help_greet() connect with command “help greet”
auto-completion
• auto-completion is already enabled in previous
example.
• if user want to do user-defined on auto-completion,
use complete_<comand> (e.g. complete_greet() )
Overrite Base Class method
• Method cmploop(intro) is the main
processing loop. Each iteration in cmdloop
call parseline and onecmd.
• Method emptyline: behavior if emptyline.
Default behavior is that rerun previous
command.
• Method default: default method if command
is not found.
Running shell command
• An exclamation point(!) map to the do_shell()
method and is intended “shelling out” to run other
commands.
• First import subprocess module.
• Second, define do_shell() method
THE LOGGING
MODULE
Brief introduction
• The logging module define standard API for
reporting error and status information.
• Both application developer and module
author benefit from this module, but has
different considerations.
Logging to file
• Use basicConfig set the log file name
The level of the events logging
tracks
Level

Numeric
value

When it’s used

DEBU Detailed information, typically of interest only when
G
diagnosing problems.
INFO Confirmation that things are working as expected.
An indication that something unexpected happened, or
WAR
indicative of some problem in the near future (e.g. ‘disk space
NING
low’). The software is still working as expected.
ERRO Due to a more serious problem, the software has not been
R
able to perform some function.
CRITIC A serious error, indicating that the program itself may be
AL
unable to continue running.

10
20
30
40
50
Best practice: logging in single file
import logging
logging.basicConfig(level=logging.WARNING) # Only the level
equal or alove this level can be displayed.
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
•Write the log to file:
logging.basicConfig(filename='example.log',level=logging.DEBU
G)
Best practice: Logging from
multiple modules
• Define logging config
in main file

• Write log in other files

More Related Content

What's hot

PYTHON PROGRAMMING
PYTHON PROGRAMMINGPYTHON PROGRAMMING
PYTHON PROGRAMMING
indupps
 
Python recursion
Python recursionPython recursion
Python recursion
Prof. Dr. K. Adisesha
 
Review functions
Review functionsReview functions
Review functions
Kgr Sushmitha
 
Function overloading
Function overloadingFunction overloading
Function overloading
Sudeshna Biswas
 
Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3
MOHIT TOMAR
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
Function overloading
Function overloadingFunction overloading
Function overloading
Selvin Josy Bai Somu
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Mohammed Sikander
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
Prem Kumar Badri
 
C++ tokens and expressions
C++ tokens and expressionsC++ tokens and expressions
C++ tokens and expressions
NabeelaNousheen
 
Python functions
Python functionsPython functions
Python functions
Prof. Dr. K. Adisesha
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
Jasleen Kaur (Chandigarh University)
 
Chapter 10 Library Function
Chapter 10 Library FunctionChapter 10 Library Function
Chapter 10 Library FunctionDeepak Singh
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
LPU
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Nikhil Pandit
 
Function
FunctionFunction
Function
yash patel
 
Python advance
Python advancePython advance
Python advance
Deepak Chandella
 
C++ Function
C++ FunctionC++ Function
C++ Function
PingLun Liao
 

What's hot (20)

PYTHON PROGRAMMING
PYTHON PROGRAMMINGPYTHON PROGRAMMING
PYTHON PROGRAMMING
 
Python recursion
Python recursionPython recursion
Python recursion
 
Review functions
Review functionsReview functions
Review functions
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3Header files of c++ unit 3 -topic 3
Header files of c++ unit 3 -topic 3
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
 
Function overloading
Function overloadingFunction overloading
Function overloading
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
 
C# Method overloading
C# Method overloadingC# Method overloading
C# Method overloading
 
C++ tokens and expressions
C++ tokens and expressionsC++ tokens and expressions
C++ tokens and expressions
 
Python functions
Python functionsPython functions
Python functions
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
 
03 function overloading
03 function overloading03 function overloading
03 function overloading
 
Chapter 10 Library Function
Chapter 10 Library FunctionChapter 10 Library Function
Chapter 10 Library Function
 
16717 functions in C++
16717 functions in C++16717 functions in C++
16717 functions in C++
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
 
Function
FunctionFunction
Function
 
Python advance
Python advancePython advance
Python advance
 
C++ Function
C++ FunctionC++ Function
C++ Function
 

Similar to Python advanced 3.the python std lib by example – application building blocks

Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
Aditya Shankar
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
Karthik Prakash
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
MuskanSony
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programming
Srinivas Narasegouda
 
Howto argparse
Howto argparseHowto argparse
Howto argparse
Manuel Cueto
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
Lennart Regebro
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
baran19901990
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
Sangharsh agarwal
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdb
Roman Podoliaka
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
baran19901990
 
Unit iii
Unit iiiUnit iii
Unit iii
snehaarao19
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
VGaneshKarthikeyan
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
Ajit Mali
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
shivam460694
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
AnkurSingh656748
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
Ihor Bobak
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
Oon Arfiandwi
 
Python
PythonPython
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
Lennart Regebro
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeDmitri Nesteruk
 

Similar to Python advanced 3.the python std lib by example – application building blocks (20)

Python for Security Professionals
Python for Security ProfessionalsPython for Security Professionals
Python for Security Professionals
 
Python and You Series
Python and You SeriesPython and You Series
Python and You Series
 
TEMPLATES IN JAVA
TEMPLATES IN JAVATEMPLATES IN JAVA
TEMPLATES IN JAVA
 
Control structures functions and modules in python programming
Control structures functions and modules in python programmingControl structures functions and modules in python programming
Control structures functions and modules in python programming
 
Howto argparse
Howto argparseHowto argparse
Howto argparse
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
07 control+structures
07 control+structures07 control+structures
07 control+structures
 
Introduction Of C++
Introduction Of C++Introduction Of C++
Introduction Of C++
 
Debugging Python with gdb
Debugging Python with gdbDebugging Python with gdb
Debugging Python with gdb
 
08 subprograms
08 subprograms08 subprograms
08 subprograms
 
Unit iii
Unit iiiUnit iii
Unit iii
 
UNIT III (2).ppt
UNIT III (2).pptUNIT III (2).ppt
UNIT III (2).ppt
 
UNIT III.ppt
UNIT III.pptUNIT III.ppt
UNIT III.ppt
 
Nitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptxNitin Mishra 0301EC201039 Internship PPT.pptx
Nitin Mishra 0301EC201039 Internship PPT.pptx
 
c++ referesher 1.pdf
c++ referesher 1.pdfc++ referesher 1.pdf
c++ referesher 1.pdf
 
Hadoop cluster performance profiler
Hadoop cluster performance profilerHadoop cluster performance profiler
Hadoop cluster performance profiler
 
Pemrograman Python untuk Pemula
Pemrograman Python untuk PemulaPemrograman Python untuk Pemula
Pemrograman Python untuk Pemula
 
Python
PythonPython
Python
 
Porting to Python 3
Porting to Python 3Porting to Python 3
Porting to Python 3
 
Unmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/InvokeUnmanaged Parallelization via P/Invoke
Unmanaged Parallelization via P/Invoke
 

More from John(Qiang) Zhang

Git and github introduction
Git and github introductionGit and github introduction
Git and github introduction
John(Qiang) Zhang
 
A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)John(Qiang) Zhang
 
Python advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modulesPython advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modulesJohn(Qiang) Zhang
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in pythonJohn(Qiang) Zhang
 

More from John(Qiang) Zhang (7)

Git and github introduction
Git and github introductionGit and github introduction
Git and github introduction
 
Python testing
Python  testingPython  testing
Python testing
 
Introduction to jython
Introduction to jythonIntroduction to jython
Introduction to jython
 
Introduction to cython
Introduction to cythonIntroduction to cython
Introduction to cython
 
A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)A useful tools in windows py2exe(optional)
A useful tools in windows py2exe(optional)
 
Python advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modulesPython advanced 3.the python std lib by example – system related modules
Python advanced 3.the python std lib by example – system related modules
 
Python advanced 2. regular expression in python
Python advanced 2. regular expression in pythonPython advanced 2. regular expression in python
Python advanced 2. regular expression in python
 

Recently uploaded

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
Kari Kakkonen
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
Frank van Harmelen
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
DianaGray10
 

Recently uploaded (20)

FIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdfFIDO Alliance Osaka Seminar: Overview.pdf
FIDO Alliance Osaka Seminar: Overview.pdf
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
DevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA ConnectDevOps and Testing slides at DASA Connect
DevOps and Testing slides at DASA Connect
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdfFIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
FIDO Alliance Osaka Seminar: Passkeys at Amazon.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyesAssuring Contact Center Experiences for Your Customers With ThousandEyes
Assuring Contact Center Experiences for Your Customers With ThousandEyes
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdfFIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
FIDO Alliance Osaka Seminar: The WebAuthn API and Discoverable Credentials.pdf
 
Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*Neuro-symbolic is not enough, we need neuro-*semantic*
Neuro-symbolic is not enough, we need neuro-*semantic*
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Connector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a buttonConnector Corner: Automate dynamic content and events by pushing a button
Connector Corner: Automate dynamic content and events by pushing a button
 

Python advanced 3.the python std lib by example – application building blocks

  • 1. THE PYTHON STD LIB BY EXAMPLE – APPLICATION BUILDING BLOCKS John Saturday, December 21, 2013
  • 2. Brief introduction • This lesson covers some of the more frequently reused building blocks that solve problems common to many applications • Command-line argument parsing: module getopt,optparse,argparse. • Interactive programs: readline, cmd, shlex,fileinput • Manage application configuration: ConfigParser • Manage log file: logging • Others: atexit, sched etc
  • 3. Module getopt – option parsing • The getopt() take 3 arguments: 1. The sequeence of arguments to be parsed. Usually it is sys.argv[1:] 2. Single-character option, following a colon(:) mean it require an argument. E.g. ab:c:, it mean a is -a simple flag, while –b and –c require an argument. 3. It is optional. If used, it is a list of long-style option names. Having suffix “=“ means ruquire an argument. E.g [‘noarg’,’witharg=‘]
  • 4. Quick example 1 # file test.py import getopt import sys opts,args = getopt.getopt(sys.argv[1:],’ab:c:’) for opt in opts: print opt •Then run command line “python test.py –a –b valb –c valc”, the output should be ('-a', '') ('-b', 'val') ('-c', 'val')
  • 5. quick example 2 # file test.py import getopt import sys opts,args = getopt.getopt(sys.argv[1:],’’,[‘opta’,’optb=‘,’optc=‘]) for opt in opts: print opt •run command line “python test.py --opta --optb val --optc val” ('--opta', '') ('--optb', 'val') ('--optc', 'val')
  • 6. Module optparse • it is a modern alternative for module getopt
  • 8. More options in add_option method • option dest: the attribute name • option default: the default value. also can be set in set_defaults method. • option type: convert the argument string to specific type, e.g. int, float,string • option choices: validation use a list of candidate strings. e.g. choices=[‘a’,’b’,’c’] . the valid value should be ‘a’, or ‘b’ or ‘c’ • option help: help message • option action: store, store_const,store_true,append,acount
  • 9. Module argparse • argparse added to python 2.7 as a replacement of optparse. • Change the OptionParser by ArgumentParser, and add_option by add_argument in previous example.
  • 10. More Options of ArgumentParser • add help automatically: parser = argparse.ArgumentParser(add_help=True) • version control: version=‘1.0’ (-v or --version will show the version number)
  • 11. More options of add_argument method • All options in optparse.add_option method. • option nargs: number of expected arguments. (? mean 0 or 1 arguments, * means 0 or all, + means 1 or all). example parser.add_argument(‘-c’,nargs=3) we need write command line “perl -c 1 2 3”
  • 12. Module getpass: handle passowrd prompts securely • print a promt and then read input from the user. • We can change the prompt: getpass(prompt=‘what is your favorite color?’)
  • 14. brief introduction • the Cmd class is used as base class for interactive shells and other command interpreters. • It can provide interactive prompt, commandline editing, and command completion.
  • 15. quick example • method do_greet() connect with command “greet” • method help_greet() connect with command “help greet”
  • 16. auto-completion • auto-completion is already enabled in previous example. • if user want to do user-defined on auto-completion, use complete_<comand> (e.g. complete_greet() )
  • 17. Overrite Base Class method • Method cmploop(intro) is the main processing loop. Each iteration in cmdloop call parseline and onecmd. • Method emptyline: behavior if emptyline. Default behavior is that rerun previous command. • Method default: default method if command is not found.
  • 18. Running shell command • An exclamation point(!) map to the do_shell() method and is intended “shelling out” to run other commands. • First import subprocess module. • Second, define do_shell() method
  • 20. Brief introduction • The logging module define standard API for reporting error and status information. • Both application developer and module author benefit from this module, but has different considerations.
  • 21. Logging to file • Use basicConfig set the log file name
  • 22. The level of the events logging tracks Level Numeric value When it’s used DEBU Detailed information, typically of interest only when G diagnosing problems. INFO Confirmation that things are working as expected. An indication that something unexpected happened, or WAR indicative of some problem in the near future (e.g. ‘disk space NING low’). The software is still working as expected. ERRO Due to a more serious problem, the software has not been R able to perform some function. CRITIC A serious error, indicating that the program itself may be AL unable to continue running. 10 20 30 40 50
  • 23. Best practice: logging in single file import logging logging.basicConfig(level=logging.WARNING) # Only the level equal or alove this level can be displayed. logging.debug('This message should go to the log file') logging.info('So should this') logging.warning('And this, too') •Write the log to file: logging.basicConfig(filename='example.log',level=logging.DEBU G)
  • 24. Best practice: Logging from multiple modules • Define logging config in main file • Write log in other files