SlideShare a Scribd company logo
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

More Related Content

What's hot

Rfselenium2 redhat
Rfselenium2 redhatRfselenium2 redhat
Rfselenium2 redhat
Joonas Jauhiainen
 
Beginning python programming
Beginning python programmingBeginning python programming
Beginning python programming
kanteshraj
 
How We Test Linux
How We Test LinuxHow We Test Linux
How We Test Linux
GlobalLogic Ukraine
 
Monorepo at Pinterest
Monorepo at PinterestMonorepo at Pinterest
Monorepo at Pinterest
Suman Karumuri
 
программное обеспечение (по)
программное обеспечение (по) программное обеспечение (по)
программное обеспечение (по)
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 1
Robert 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 kite
Christian 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 Linker
Gonç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 entornos
Micael 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 example
corehard_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 use
arun.arwachin
 
Inroduction to golang
Inroduction to golangInroduction to golang
Inroduction to golang
Yoni Davidson
 
Introduction to protocol buffer
Introduction to protocol bufferIntroduction to protocol buffer
Introduction to protocol buffer
Tim (文昌)
 
Performance Profiling Tools and Tricks
Performance Profiling Tools and TricksPerformance Profiling Tools and Tricks
Performance Profiling Tools and Tricks
Phase2
 
Go Lang
Go LangGo Lang
Lua vs python
Lua vs pythonLua vs python
Lua vs python
HoChul Shin
 

What's hot (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
 

Viewers also liked

Deploying Django with Ansible
Deploying Django with AnsibleDeploying Django with Ansible
Deploying Django with Ansible
andrewmirskynet
 
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
Rebecca 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 Analysis
jeresig
 
GNU Parallel - Ole Tange
GNU Parallel - Ole TangeGNU Parallel - Ole Tange
GNU Parallel - Ole Tange
FSCONS
 
Spring Framework - Expression Language
Spring Framework - Expression LanguageSpring Framework - Expression Language
Spring Framework - Expression Language
Dzmitry 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 Story
Randy Bias
 
OMA Lightweight M2M Tutorial
OMA Lightweight M2M TutorialOMA Lightweight M2M Tutorial
OMA Lightweight M2M Tutorial
zdshelby
 
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
Ian 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 MVC
digitalsonic
 
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
jaguardesignstudio
 
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
 
What is strategy?
What is strategy?What is strategy?
What is strategy?
Dr. Marc Sniukas
 
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
JamesAltucher
 
The 5 Secrets of Networking
The 5 Secrets of NetworkingThe 5 Secrets of Networking
The 5 Secrets of Networking
Angel L. Ramos, MBA
 
no brand is your friend
no brand is your friendno brand is your friend
no brand is your friend
Michael Paredrakos
 
Preparing to fail
Preparing to failPreparing to fail
Preparing to fail
aweyenberg
 
How Google Works
How Google WorksHow Google Works
How Google Works
Eric Schmidt
 

Viewers also liked (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 to How to write a well-behaved Python command line application

Introduction to Python Programming
Introduction to Python ProgrammingIntroduction to Python Programming
Introduction to Python Programming
Akhil Kaushik
 
Introduction to python
Introduction to pythonIntroduction to python
Introduction to python
Mohammed 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_vfinal
Prof. Wim Van Criekinge
 
python presntation 2.pptx
python presntation 2.pptxpython presntation 2.pptx
python presntation 2.pptx
Arpittripathi45
 
MODULE 1.pptx
MODULE 1.pptxMODULE 1.pptx
MODULE 1.pptx
KPDDRAVIDIAN
 
Introduction to Python for Security Professionals
Introduction to Python for Security ProfessionalsIntroduction to Python for Security Professionals
Introduction to Python for Security Professionals
Andrew McNicol
 
Python Programming1.ppt
Python Programming1.pptPython Programming1.ppt
Python Programming1.ppt
Rehnawilson1
 
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
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
Denis 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 Calls
Vandana Salve
 
Introduction to Python Programming Basics
Introduction  to  Python  Programming BasicsIntroduction  to  Python  Programming Basics
Introduction to Python Programming Basics
Dhana malar
 
Reproducible research concepts and tools
Reproducible research concepts and toolsReproducible research concepts and tools
Reproducible research concepts and tools
C. 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).pdf
RahulSingh190790
 
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
Raza Ul Mustafa
 
python intro and installation.pptx
python intro and installation.pptxpython intro and installation.pptx
python intro and installation.pptx
adityakumawat625
 
Embedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals masterEmbedded c c++ programming fundamentals master
Embedded c c++ programming fundamentals master
Hossam Hassan
 

Similar to 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
 

Recently uploaded

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
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
ThousandEyes
 
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
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
Safe Software
 
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
 
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
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
SOFTTECHHUB
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
Jen Stirrup
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
Kari Kakkonen
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
nkrafacyberclub
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
UiPathCommunity
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
Globus
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
James Anderson
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
UiPathCommunity
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
Alex Pruden
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
sonjaschweigert1
 
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
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
Vlad Stirbu
 

Recently uploaded (20)

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
 
Assure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyesAssure Contact Center Experiences for Your Customers With ThousandEyes
Assure Contact Center Experiences for Your Customers With ThousandEyes
 
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
 
Essentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FMEEssentials of Automations: The Art of Triggers and Actions in FME
Essentials of Automations: The Art of Triggers and Actions in FME
 
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
 
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
 
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
Why You Should Replace Windows 11 with Nitrux Linux 3.5.0 for enhanced perfor...
 
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...The Metaverse and AI: how can decision-makers harness the Metaverse for their...
The Metaverse and AI: how can decision-makers harness the Metaverse for their...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Climate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing DaysClimate Impact of Software Testing at Nordic Testing Days
Climate Impact of Software Testing at Nordic Testing Days
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptxSecstrike : Reverse Engineering & Pwnable tools for CTF.pptx
Secstrike : Reverse Engineering & Pwnable tools for CTF.pptx
 
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
Dev Dives: Train smarter, not harder – active learning and UiPath LLMs for do...
 
Enhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZEnhancing Performance with Globus and the Science DMZ
Enhancing Performance with Globus and the Science DMZ
 
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...
 
UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..UiPath Community Day Dubai: AI at Work..
UiPath Community Day Dubai: AI at Work..
 
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex ProofszkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
zkStudyClub - Reef: Fast Succinct Non-Interactive Zero-Knowledge Regex Proofs
 
A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...A tale of scale & speed: How the US Navy is enabling software delivery from l...
A tale of scale & speed: How the US Navy is enabling software delivery from l...
 
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
 
Quantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIsQuantum Computing: Current Landscape and the Future Role of APIs
Quantum Computing: Current Landscape and the Future Role of APIs
 

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