SlideShare una empresa de Scribd logo
1 de 34
Descargar para leer sin conexión
How to write a well-behaved
Python command line
application



                       PyCon AU 2012
                              Tutorial
                        Graeme Cross
This is an introduction to…
• Writing robust, maintainable command line
  applications
• Easily processing command line options
• Filters and files for input/output
• Handling errors and signals
• Testing your app
• Documenting and packaging your app
I am assuming…
•   You know how to program (at least a bit!)
•   Some familiarity with Python basics
•   Python 2.6 or 2.7 (but not Python 3)
•   Know the difference between:
    – GUI
    – Command prompt (C:> or ~$ )
The examples and these notes
• We will use a number of demo scripts
  – This is an interactive tutorial
  – If you have a laptop, join in!
  – We will use ipython for the demos
• Code is on USB sticks being passed around
• Code & these notes are also at:
  http://www.curiousvenn.com/
ipython
• A very flexible Python shell
• Works on all platforms
• Lots of really nice features:
  – Command line editing with history
  – Coloured syntax
  – Edit and run within the shell
  – Web notebooks, Visual Studio, Qt, …
  – %lsmagic
• http://ipython.org/
  http://ipython.org/presentation.html
Prelude
The command line
• One liners → shell scripts → applications
• Lots of interfaces:
  – Files
  – Pipes
  – User input/output
  – Processes
  – Networking
• The Unix model: lots of small tools that
  can be combined in lots of useful ways
What is a “well-behaved” app?
• Does one thing well
• Flexible
  – eg. handles input from files or pipes
• Robustly handles bad input data
• Gracefully handles errors
• Well-documented for new users
Why Python for the command line?
• Available on a wide range of platforms
• Readable, consistent syntax
  – Easy to write & easy to maintain
• Scales well for large apps & libraries
• Lots of modules = excellent support for:
  – Operating system functions (eg POSIX)
  – Networking
  – File systems
Why not Python?
• Simple one-liners often easier in bash
• eg. Neatly list all users in an LDAP group:
 smbldap-groupshow $1 | tail -1 | tr [:lower:] [:upper:] | sed s/,/ /g | sed s/MEMBERUID: //


• Some operating systems are rumoured to
  not ship with Python
• Any other reasons??? Ummmm.....
Be platform aware
• Lots of standard library support
• No excuse to not support other platforms!
• Recommended modules for portability:
  – os
  – os.path
  – shutil
  – fileinput
  – tempfile
• Lots of other modules in PyPI
Here we go!
if __name__ == '__main__'
• For any Python script, break it up into:
  – Functions
  – A “main” function, called from command line
• Makes it easy to:
  – Test functionality
  – Reuse functions
• Example: main1.py
Anatomy of the command line
Files
•   Reading, writing & appending to files
•   Text or binary formats
•   This is a tutorial on its own!
•   Example: file1.py
•   Example: file2.py
Pipes
• Instead of a filename, pipe input/output
• Create chains of tools
• Standard pipes:
  – Input: stdin
  – Output: stdout & stderr
• The sys module has support for these
• The fileinput module supports reading
  from stdin and files
• Example: stdout.py
Argument parsing
• Allow the user to specify arguments
  – Edit the script?
  – Modify a configuration file?
  – Specify arguments on the command line
• Need to handle:
  – Flags: -h or --help
  – Strings: “Run Forrest, Run”
  – Pipes
  – Invalid number of commands
  – Ideally: type checking, range checking, etc.
Argument parsing options
• Standard library: 3 different modules!
• Recommended module: argparse
• A series of examples:
  – uniq1.py → uniq4.py
  – uniqsort.py
• Lots more in PyPI!
• Recommended modules from PyPI:
  – clint
  – docopt
Argument parsing thoughts
• Always provide help at the command line
• Be consistent
  – Short and/or long flags?
  – Intuitive?
  – Ensure dangerous flags are obvious
  – Sensible mnemonics for abbreviated flags
Configuration files
• Useful for arguments that:
  – Could change
  – Don't change very often
  – Are probably machine- or user-specific
• Number of standard library modules:
  – ConfigParser (INI file format)
  – json (human & machine readable)
  – xml.* (if you must)
  – As well as csv, plistlib (for Mac .plist)
• Don't roll your own config file format!
Calling commands
• Python can execute other applications
• The subprocess module
  – The best of the standard library modules
  – Spawn a process
  – Read/write the input/output/error pipes
  – Get return code for error checking
  – Does not scale well
  – Examples: subprocess1.py & subprocess2.py
Calling commands, the easy way
• The envoy module (from PyPI)
  – A whole lot easier
  – More Pythonic
  – Recommended alternative to the subprocess
    module
  – https://github.com/kennethreitz/envoy/
  – Example: envoy1.py
Error handling
• Robust apps gracefully handle errors
  – Catch (all reasonable) errors
  – Report errors to the user
• Silently failing is rarely acceptable
• Blowing up is not much better!
Error handling: catching errors
• Exceptions
  – Recommended way to handle errors in Python
  – Also used for non-error notification
  – Example: exception1.py
• Error codes
  – Some functions return an error code (instead of
    raising an exception)
  – Common with C/C++ code interfaced to Python
  – Best to wrap these and then raise an exception
Error handling: reporting errors
• For command line apps:
  – Print to stderr
  – Don't just print errors (to stdout)
• For daemons/services:
  – Dedicated log file for the application
  – Write to the operating system event log(s)
• Use the logger module
  – Don't roll your own!
  – http://docs.python.org/library/logging.html
Signal handling
• Support is provided via the signal module
  – Can raise signals
  – Can handle incoming signals
• Useful to catch keyboard interrupts
  – eg. interrupt a long running process
• Good form to not ignore system exit events
• Example: signal1.py
• Example: signal2.py
Let's take a breather...
Testing
• Well-tested = happy users and maintainers
  – Design your app for unit testing
  – doctest and unittest are two good approaches
  – nose (from PyPI) builds on unittest
  – mock for mock testing
  – pylint and pychecker: good “lint” tools
• Python Testing Tools Taxonomy:
  – Links to testing libraries and tools
  – http://wiki.python.org/moin/PythonTestingToolsTaxonomy
Documenting your application
• Essential:
  – README.txt (overview)
  – LICENSE.txt (essential)
  – CHANGES.txt (application changelog)
  – User documentation/manual
• Formats
  – Text file
  – HTML (for online or offline use)
  – man page
  – Example: rsync man page
Packaging your application
• Another whole tutorial topic!
• Use the standard Python distribution tools:
  – setup.py
  – PyPI (for public distribution)
  – http://guide.python-distribute.org/
• Other approaches for specific platforms:
  – Debian package (.deb)
  – RedHat/SuSE/CentOS (.rpm)
  – MSI (Windows)
  – etc.
This is the end...
For more information...
• The Python tutorial
  – http://python.org/
• Python Module of the Week
  – http://www.doughellmann.com/PyMOTW/
Some good books…
• “Learning Python”, Mark Lutz
• “Hello Python”, Anthony Briggs
In the beginning
• http://www.cryptonomicon.com/beginning.html

Más contenido relacionado

La actualidad más candente

Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programmingkanteshraj
 
программное обеспечение (по)
программное обеспечение (по) программное обеспечение (по)
программное обеспечение (по) victoria_4
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Robert Stern
 
Development and deployment with composer and kite
Development and deployment with composer and kiteDevelopment and deployment with composer and kite
Development and deployment with composer and kiteChristian Opitz
 
Clang Analyzer Tool Review
Clang Analyzer Tool ReviewClang Analyzer Tool Review
Clang Analyzer Tool ReviewDoug Schuster
 
Decision making - for loop , nested loop ,if-else statements , switch in goph...
Decision making - for loop , nested loop ,if-else statements , switch in goph...Decision making - for loop , nested loop ,if-else statements , switch in goph...
Decision making - for loop , nested loop ,if-else statements , switch in goph...sangam biradar
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerGonçalo Gomes
 
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Aniruddha Chakrabarti
 
Golang (Go Programming Language)
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)ShubhamMishra485
 
Testing fácil con Docker: Gestiona dependencias y unifica entornos
Testing fácil con Docker: Gestiona dependencias y unifica entornosTesting fácil con Docker: Gestiona dependencias y unifica entornos
Testing fácil con Docker: Gestiona dependencias y unifica entornosMicael Gallego
 
Mixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting exampleMixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting examplecorehard_by
 
Some wonderful Linux softwares for daily use
Some wonderful Linux softwares for daily useSome wonderful Linux softwares for daily use
Some wonderful Linux softwares for daily usearun.arwachin
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golangYoni Davidson
 
Introduction to protocol buffer
Introduction to protocol bufferIntroduction to protocol buffer
Introduction to protocol bufferTim (文昌)
 
Performance Profiling Tools and Tricks
Performance Profiling Tools and TricksPerformance Profiling Tools and Tricks
Performance Profiling Tools and TricksPhase2
 

La actualidad más candente (20)

Rfselenium2 redhat
Rfselenium2 redhatRfselenium2 redhat
Rfselenium2 redhat
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programming
 
How We Test Linux
How We Test LinuxHow We Test Linux
How We Test Linux
 
Monorepo at Pinterest
Monorepo at PinterestMonorepo at Pinterest
Monorepo at Pinterest
 
программное обеспечение (по)
программное обеспечение (по) программное обеспечение (по)
программное обеспечение (по)
 
Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1Golang basics for Java developers - Part 1
Golang basics for Java developers - Part 1
 
Development and deployment with composer and kite
Development and deployment with composer and kiteDevelopment and deployment with composer and kite
Development and deployment with composer and kite
 
Clang Analyzer Tool Review
Clang Analyzer Tool ReviewClang Analyzer Tool Review
Clang Analyzer Tool Review
 
Decision making - for loop , nested loop ,if-else statements , switch in goph...
Decision making - for loop , nested loop ,if-else statements , switch in goph...Decision making - for loop , nested loop ,if-else statements , switch in goph...
Decision making - for loop , nested loop ,if-else statements , switch in goph...
 
Whirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic LinkerWhirlwind tour of the Runtime Dynamic Linker
Whirlwind tour of the Runtime Dynamic Linker
 
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
Mphasis Digital - Use Go (gloang) for system programming, distributed systems...
 
Golang (Go Programming Language)
Golang (Go Programming Language)Golang (Go Programming Language)
Golang (Go Programming Language)
 
Testing fácil con Docker: Gestiona dependencias y unifica entornos
Testing fácil con Docker: Gestiona dependencias y unifica entornosTesting fácil con Docker: Gestiona dependencias y unifica entornos
Testing fácil con Docker: Gestiona dependencias y unifica entornos
 
Mixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting exampleMixing d ps building architecture on the cross cutting example
Mixing d ps building architecture on the cross cutting example
 
Some wonderful Linux softwares for daily use
Some wonderful Linux softwares for daily useSome wonderful Linux softwares for daily use
Some wonderful Linux softwares for daily use
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
 
Introduction to protocol buffer
Introduction to protocol bufferIntroduction to protocol buffer
Introduction to protocol buffer
 
Performance Profiling Tools and Tricks
Performance Profiling Tools and TricksPerformance Profiling Tools and Tricks
Performance Profiling Tools and Tricks
 
Go Lang
Go LangGo Lang
Go Lang
 
Lua vs python
Lua vs pythonLua vs python
Lua vs python
 

Destacado

Deploying Django with Ansible
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansibleandrewmirskynet
 
Using Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeRebecca Murphey
 
EmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image AnalysisEmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image Analysisjeresig
 
GNU Parallel - Ole Tange
GNU Parallel - Ole TangeGNU Parallel - Ole Tange
GNU Parallel - Ole TangeFSCONS
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression LanguageDzmitry Naskou
 
How Emacs changed my life
How Emacs changed my lifeHow Emacs changed my life
How Emacs changed my lifeyukihiro_matz
 
Pets vs. Cattle: The Elastic Cloud Story
Pets vs. Cattle: The Elastic Cloud StoryPets vs. Cattle: The Elastic Cloud Story
Pets vs. Cattle: The Elastic Cloud StoryRandy Bias
 
OMA Lightweight M2M Tutorial
OMA Lightweight M2M TutorialOMA Lightweight M2M Tutorial
OMA Lightweight M2M Tutorialzdshelby
 
Getting started with AWS IoT on Raspberry Pi
Getting started with AWS IoT on Raspberry PiGetting started with AWS IoT on Raspberry Pi
Getting started with AWS IoT on Raspberry PiIan Massingham
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Jérôme Petazzoni
 
20 Habits Of Mindful People (Mindfulness)
20 Habits Of Mindful People (Mindfulness)20 Habits Of Mindful People (Mindfulness)
20 Habits Of Mindful People (Mindfulness)Barrie Davenport
 
RESTful Web Services with Spring MVC
RESTful Web Services with Spring MVCRESTful Web Services with Spring MVC
RESTful Web Services with Spring MVCdigitalsonic
 
Why Zsh is Cooler than Your Shell
Why Zsh is Cooler than Your ShellWhy Zsh is Cooler than Your Shell
Why Zsh is Cooler than Your Shelljaguardesignstudio
 
Securing Serverless Workloads with Cognito and API Gateway Part II - AWS Secu...
Securing Serverless Workloads with Cognito and API Gateway Part II - AWS Secu...Securing Serverless Workloads with Cognito and API Gateway Part II - AWS Secu...
Securing Serverless Workloads with Cognito and API Gateway Part II - AWS Secu...Amazon Web Services
 
The Power of No: 12 Things to Say “No” To Today
The Power of No: 12 Things to Say “No” To TodayThe Power of No: 12 Things to Say “No” To Today
The Power of No: 12 Things to Say “No” To TodayJamesAltucher
 
Preparing to fail
Preparing to failPreparing to fail
Preparing to failaweyenberg
 

Destacado (20)

Deploying Django with Ansible
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansible
 
Using Objects to Organize your jQuery Code
Using Objects to Organize your jQuery CodeUsing Objects to Organize your jQuery Code
Using Objects to Organize your jQuery Code
 
EmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image AnalysisEmpireJS: Hacking Art with Node js and Image Analysis
EmpireJS: Hacking Art with Node js and Image Analysis
 
GNU Parallel - Ole Tange
GNU Parallel - Ole TangeGNU Parallel - Ole Tange
GNU Parallel - Ole Tange
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
 
How Emacs changed my life
How Emacs changed my lifeHow Emacs changed my life
How Emacs changed my life
 
Pets vs. Cattle: The Elastic Cloud Story
Pets vs. Cattle: The Elastic Cloud StoryPets vs. Cattle: The Elastic Cloud Story
Pets vs. Cattle: The Elastic Cloud Story
 
OMA Lightweight M2M Tutorial
OMA Lightweight M2M TutorialOMA Lightweight M2M Tutorial
OMA Lightweight M2M Tutorial
 
Getting started with AWS IoT on Raspberry Pi
Getting started with AWS IoT on Raspberry PiGetting started with AWS IoT on Raspberry Pi
Getting started with AWS IoT on Raspberry Pi
 
Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?Docker and Go: why did we decide to write Docker in Go?
Docker and Go: why did we decide to write Docker in Go?
 
20 Habits Of Mindful People (Mindfulness)
20 Habits Of Mindful People (Mindfulness)20 Habits Of Mindful People (Mindfulness)
20 Habits Of Mindful People (Mindfulness)
 
RESTful Web Services with Spring MVC
RESTful Web Services with Spring MVCRESTful Web Services with Spring MVC
RESTful Web Services with Spring MVC
 
Why Zsh is Cooler than Your Shell
Why Zsh is Cooler than Your ShellWhy Zsh is Cooler than Your Shell
Why Zsh is Cooler than Your Shell
 
Securing Serverless Workloads with Cognito and API Gateway Part II - AWS Secu...
Securing Serverless Workloads with Cognito and API Gateway Part II - AWS Secu...Securing Serverless Workloads with Cognito and API Gateway Part II - AWS Secu...
Securing Serverless Workloads with Cognito and API Gateway Part II - AWS Secu...
 
What is strategy?
What is strategy?What is strategy?
What is strategy?
 
The Power of No: 12 Things to Say “No” To Today
The Power of No: 12 Things to Say “No” To TodayThe Power of No: 12 Things to Say “No” To Today
The Power of No: 12 Things to Say “No” To Today
 
The 5 Secrets of Networking
The 5 Secrets of NetworkingThe 5 Secrets of Networking
The 5 Secrets of Networking
 
no brand is your friend
no brand is your friendno brand is your friend
no brand is your friend
 
Preparing to fail
Preparing to failPreparing to fail
Preparing to fail
 
How Google Works
How Google WorksHow Google Works
How Google Works
 

Similar a How to write a well-behaved Python command line application

Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python ProgrammingAkhil Kaushik
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to pythonMohammed Rafi
 
Austin Python Learners Meetup - Everything you need to know about programming...
Austin Python Learners Meetup - Everything you need to know about programming...Austin Python Learners Meetup - Everything you need to know about programming...
Austin Python Learners Meetup - Everything you need to know about programming...Danny Mulligan
 
2015 bioinformatics python_introduction_wim_vancriekinge_vfinal
2015 bioinformatics python_introduction_wim_vancriekinge_vfinal2015 bioinformatics python_introduction_wim_vancriekinge_vfinal
2015 bioinformatics python_introduction_wim_vancriekinge_vfinalProf. Wim Van Criekinge
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptxArpittripathi45
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsAndrew McNicol
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.pptRehnawilson1
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh MalothBhavsingh Maloth
 
Reproducibility and automation of machine learning process
Reproducibility and automation of machine learning processReproducibility and automation of machine learning process
Reproducibility and automation of machine learning processDenis Dus
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programmingChetan Giridhar
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Mohan Arumugam
 
Introduction to System Calls
Introduction to System CallsIntroduction to System Calls
Introduction to System CallsVandana Salve
 
Introduction to Python Programming Basics
Introduction  to  Python  Programming BasicsIntroduction  to  Python  Programming Basics
Introduction to Python Programming BasicsDhana malar
 
Reproducible research concepts and tools
Reproducible research concepts and toolsReproducible research concepts and tools
Reproducible research concepts and toolsC. Tobin Magle
 
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdfDr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdfRahulSingh190790
 
Python Intro Slides for Students CSC-148 Chapter 1
Python Intro Slides for Students CSC-148  Chapter 1Python Intro Slides for Students CSC-148  Chapter 1
Python Intro Slides for Students CSC-148 Chapter 1Raza Ul Mustafa
 
python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptxadityakumawat625
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterHossam Hassan
 

Similar a How to write a well-behaved Python command line application (20)

Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
 
Austin Python Learners Meetup - Everything you need to know about programming...
Austin Python Learners Meetup - Everything you need to know about programming...Austin Python Learners Meetup - Everything you need to know about programming...
Austin Python Learners Meetup - Everything you need to know about programming...
 
2015 bioinformatics python_introduction_wim_vancriekinge_vfinal
2015 bioinformatics python_introduction_wim_vancriekinge_vfinal2015 bioinformatics python_introduction_wim_vancriekinge_vfinal
2015 bioinformatics python_introduction_wim_vancriekinge_vfinal
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
 
MODULE 1.pptx
MODULE 1.pptxMODULE 1.pptx
MODULE 1.pptx
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.ppt
 
Python Tutorial Part 2
Python Tutorial Part 2Python Tutorial Part 2
Python Tutorial Part 2
 
web programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Malothweb programming UNIT VIII python by Bhavsingh Maloth
web programming UNIT VIII python by Bhavsingh Maloth
 
Reproducibility and automation of machine learning process
Reproducibility and automation of machine learning processReproducibility and automation of machine learning process
Reproducibility and automation of machine learning process
 
Tutorial on-python-programming
Tutorial on-python-programmingTutorial on-python-programming
Tutorial on-python-programming
 
Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)Python-Yesterday Today Tomorrow(What's new?)
Python-Yesterday Today Tomorrow(What's new?)
 
Introduction to System Calls
Introduction to System CallsIntroduction to System Calls
Introduction to System Calls
 
Introduction to Python Programming Basics
Introduction  to  Python  Programming BasicsIntroduction  to  Python  Programming Basics
Introduction to Python Programming Basics
 
Reproducible research concepts and tools
Reproducible research concepts and toolsReproducible research concepts and tools
Reproducible research concepts and tools
 
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdfDr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
Dr. Tanvi FOCP Unit-2 Session-1 PPT (Revised).pdf
 
Python Intro Slides for Students CSC-148 Chapter 1
Python Intro Slides for Students CSC-148  Chapter 1Python Intro Slides for Students CSC-148  Chapter 1
Python Intro Slides for Students CSC-148 Chapter 1
 
python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptx
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
 

Último

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Farhan Tariq
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rick Flair
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Hiroshi SHIBATA
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxLoriGlavin3
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersRaghuram Pandurangan
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxLoriGlavin3
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfNeo4j
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...Wes McKinney
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.Curtis Poe
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesThousandEyes
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationKnoldus Inc.
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfpanagenda
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsPixlogix Infotech
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPathCommunity
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesKari Kakkonen
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Scott Andery
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Mark Goldstein
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityIES VE
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxLoriGlavin3
 

Último (20)

Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...Genislab builds better products and faster go-to-market with Lean project man...
Genislab builds better products and faster go-to-market with Lean project man...
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...Rise of the Machines: Known As Drones...
Rise of the Machines: Known As Drones...
 
Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024Long journey of Ruby standard library at RubyConf AU 2024
Long journey of Ruby standard library at RubyConf AU 2024
 
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptxUse of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
Use of FIDO in the Payments and Identity Landscape: FIDO Paris Seminar.pptx
 
Generative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information DevelopersGenerative AI for Technical Writer or Information Developers
Generative AI for Technical Writer or Information Developers
 
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptxDigital Identity is Under Attack: FIDO Paris Seminar.pptx
Digital Identity is Under Attack: FIDO Paris Seminar.pptx
 
Connecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdfConnecting the Dots for Information Discovery.pdf
Connecting the Dots for Information Discovery.pdf
 
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
The Future Roadmap for the Composable Data Stack - Wes McKinney - Data Counci...
 
How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.How AI, OpenAI, and ChatGPT impact business and software.
How AI, OpenAI, and ChatGPT impact business and software.
 
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyesHow to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
How to Effectively Monitor SD-WAN and SASE Environments with ThousandEyes
 
Data governance with Unity Catalog Presentation
Data governance with Unity Catalog PresentationData governance with Unity Catalog Presentation
Data governance with Unity Catalog Presentation
 
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdfSo einfach geht modernes Roaming fuer Notes und Nomad.pdf
So einfach geht modernes Roaming fuer Notes und Nomad.pdf
 
The Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and ConsThe Ultimate Guide to Choosing WordPress Pros and Cons
The Ultimate Guide to Choosing WordPress Pros and Cons
 
UiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to HeroUiPath Community: Communication Mining from Zero to Hero
UiPath Community: Communication Mining from Zero to Hero
 
Testing tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examplesTesting tools and AI - ideas what to try with some tool examples
Testing tools and AI - ideas what to try with some tool examples
 
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
Enhancing User Experience - Exploring the Latest Features of Tallyman Axis Lo...
 
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
Arizona Broadband Policy Past, Present, and Future Presentation 3/25/24
 
Decarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a realityDecarbonising Buildings: Making a net-zero built environment a reality
Decarbonising Buildings: Making a net-zero built environment a reality
 
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptxA Deep Dive on Passkeys: FIDO Paris Seminar.pptx
A Deep Dive on Passkeys: FIDO Paris Seminar.pptx
 

How to write a well-behaved Python command line application

  • 1. How to write a well-behaved Python command line application PyCon AU 2012 Tutorial Graeme Cross
  • 2. This is an introduction to… • Writing robust, maintainable command line applications • Easily processing command line options • Filters and files for input/output • Handling errors and signals • Testing your app • Documenting and packaging your app
  • 3. I am assuming… • You know how to program (at least a bit!) • Some familiarity with Python basics • Python 2.6 or 2.7 (but not Python 3) • Know the difference between: – GUI – Command prompt (C:> or ~$ )
  • 4. The examples and these notes • We will use a number of demo scripts – This is an interactive tutorial – If you have a laptop, join in! – We will use ipython for the demos • Code is on USB sticks being passed around • Code & these notes are also at: http://www.curiousvenn.com/
  • 5. ipython • A very flexible Python shell • Works on all platforms • Lots of really nice features: – Command line editing with history – Coloured syntax – Edit and run within the shell – Web notebooks, Visual Studio, Qt, … – %lsmagic • http://ipython.org/ http://ipython.org/presentation.html
  • 7. The command line • One liners → shell scripts → applications • Lots of interfaces: – Files – Pipes – User input/output – Processes – Networking • The Unix model: lots of small tools that can be combined in lots of useful ways
  • 8. What is a “well-behaved” app? • Does one thing well • Flexible – eg. handles input from files or pipes • Robustly handles bad input data • Gracefully handles errors • Well-documented for new users
  • 9. Why Python for the command line? • Available on a wide range of platforms • Readable, consistent syntax – Easy to write & easy to maintain • Scales well for large apps & libraries • Lots of modules = excellent support for: – Operating system functions (eg POSIX) – Networking – File systems
  • 10. Why not Python? • Simple one-liners often easier in bash • eg. Neatly list all users in an LDAP group: smbldap-groupshow $1 | tail -1 | tr [:lower:] [:upper:] | sed s/,/ /g | sed s/MEMBERUID: // • Some operating systems are rumoured to not ship with Python • Any other reasons??? Ummmm.....
  • 11. Be platform aware • Lots of standard library support • No excuse to not support other platforms! • Recommended modules for portability: – os – os.path – shutil – fileinput – tempfile • Lots of other modules in PyPI
  • 13. if __name__ == '__main__' • For any Python script, break it up into: – Functions – A “main” function, called from command line • Makes it easy to: – Test functionality – Reuse functions • Example: main1.py
  • 14. Anatomy of the command line
  • 15. Files • Reading, writing & appending to files • Text or binary formats • This is a tutorial on its own! • Example: file1.py • Example: file2.py
  • 16. Pipes • Instead of a filename, pipe input/output • Create chains of tools • Standard pipes: – Input: stdin – Output: stdout & stderr • The sys module has support for these • The fileinput module supports reading from stdin and files • Example: stdout.py
  • 17. Argument parsing • Allow the user to specify arguments – Edit the script? – Modify a configuration file? – Specify arguments on the command line • Need to handle: – Flags: -h or --help – Strings: “Run Forrest, Run” – Pipes – Invalid number of commands – Ideally: type checking, range checking, etc.
  • 18. Argument parsing options • Standard library: 3 different modules! • Recommended module: argparse • A series of examples: – uniq1.py → uniq4.py – uniqsort.py • Lots more in PyPI! • Recommended modules from PyPI: – clint – docopt
  • 19. Argument parsing thoughts • Always provide help at the command line • Be consistent – Short and/or long flags? – Intuitive? – Ensure dangerous flags are obvious – Sensible mnemonics for abbreviated flags
  • 20. Configuration files • Useful for arguments that: – Could change – Don't change very often – Are probably machine- or user-specific • Number of standard library modules: – ConfigParser (INI file format) – json (human & machine readable) – xml.* (if you must) – As well as csv, plistlib (for Mac .plist) • Don't roll your own config file format!
  • 21. Calling commands • Python can execute other applications • The subprocess module – The best of the standard library modules – Spawn a process – Read/write the input/output/error pipes – Get return code for error checking – Does not scale well – Examples: subprocess1.py & subprocess2.py
  • 22. Calling commands, the easy way • The envoy module (from PyPI) – A whole lot easier – More Pythonic – Recommended alternative to the subprocess module – https://github.com/kennethreitz/envoy/ – Example: envoy1.py
  • 23. Error handling • Robust apps gracefully handle errors – Catch (all reasonable) errors – Report errors to the user • Silently failing is rarely acceptable • Blowing up is not much better!
  • 24. Error handling: catching errors • Exceptions – Recommended way to handle errors in Python – Also used for non-error notification – Example: exception1.py • Error codes – Some functions return an error code (instead of raising an exception) – Common with C/C++ code interfaced to Python – Best to wrap these and then raise an exception
  • 25. Error handling: reporting errors • For command line apps: – Print to stderr – Don't just print errors (to stdout) • For daemons/services: – Dedicated log file for the application – Write to the operating system event log(s) • Use the logger module – Don't roll your own! – http://docs.python.org/library/logging.html
  • 26. Signal handling • Support is provided via the signal module – Can raise signals – Can handle incoming signals • Useful to catch keyboard interrupts – eg. interrupt a long running process • Good form to not ignore system exit events • Example: signal1.py • Example: signal2.py
  • 27. Let's take a breather...
  • 28. Testing • Well-tested = happy users and maintainers – Design your app for unit testing – doctest and unittest are two good approaches – nose (from PyPI) builds on unittest – mock for mock testing – pylint and pychecker: good “lint” tools • Python Testing Tools Taxonomy: – Links to testing libraries and tools – http://wiki.python.org/moin/PythonTestingToolsTaxonomy
  • 29. Documenting your application • Essential: – README.txt (overview) – LICENSE.txt (essential) – CHANGES.txt (application changelog) – User documentation/manual • Formats – Text file – HTML (for online or offline use) – man page – Example: rsync man page
  • 30. Packaging your application • Another whole tutorial topic! • Use the standard Python distribution tools: – setup.py – PyPI (for public distribution) – http://guide.python-distribute.org/ • Other approaches for specific platforms: – Debian package (.deb) – RedHat/SuSE/CentOS (.rpm) – MSI (Windows) – etc.
  • 31. This is the end...
  • 32. For more information... • The Python tutorial – http://python.org/ • Python Module of the Week – http://www.doughellmann.com/PyMOTW/
  • 33. Some good books… • “Learning Python”, Mark Lutz • “Hello Python”, Anthony Briggs
  • 34. In the beginning • http://www.cryptonomicon.com/beginning.html