SlideShare una empresa de Scribd logo
1 de 13
Developing a nice template for new scripts
#!/usr/bin/python import sys import random def scramble(word): if len(word) < 4: return word innards = list(word[1:-1]) random.shuffle(innards) return word[0] + ''.join(innards) + word[-1] while 1: line = sys.stdin.readline() if not line: break sys.stdout.write(' '.join([scramble(w) for w in line.split()]) + '') In the beginning
Adding basic niceties #!/usr/bin/ env  python # -*- coding: utf-8 -*- import sys import random def scramble(word): if len(word) < 4: return word innards = list(word[1:-1]) random.shuffle(innards) return word[0] + ''.join(innards) + word[-1] def _main(): while 1: line = sys.stdin.readline() if not line: break sys.stdout.write(' '.join([scramble(w) for w in line.split()]) + '') return 0 if __name__ == &quot;__main__&quot;: sys.exit(_main())
stephenj@lords:~$ python Python 2.5.2 (r252:60911, Oct  5 2008, 19:24:49)  [GCC 4.3.2] on linux2 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. >>> import scramble >>> scramble.scramble('scramble') 'srlacmbe' >>>
from optparse import OptionParser ... def _main(filename=None): ... if __name__ == &quot;__main__&quot;: usage = &quot;usage: %prog [options] [filename]&quot; parser = OptionParser(usage=usage) parser.add_option('--profile', '-P', help  = &quot;Print out profiling stats&quot;, action  = 'store_true') parser.add_option('--test', '-t', help  ='Run doctests', action = 'store_true') parser.add_option('--verbose', '-v', help  ='print debugging output', action = 'store_true') (options, args) = parser.parse_args() # Assign non-flag arguments here. filename = None if len(args) > 0: filename = args[0]
stephenj@lords:~$ python scramble.py -h Usage: scramble.py [options] [filename] Options: -h, --help  show this help message and exit -P, --profile  Print out profiling stats -t, --test  Run doctests -v, --verbose  print debugging output
Tests are good def scramble(word): &quot;&quot;&quot; Returns a scrambled version if it is longer than 3 chars.  Scrambling preserves the first and last characters. >>> scramble('a') 'a' >>> scramble('an') 'an' >>> scramble('the') 'the' >>> scramble('cart') in ['cart', 'crat'] True &quot;&quot;&quot; if len(word) < 4: return word innards = list(word[1:-1]) random.shuffle(innards) return word[0] + ''.join(innards) + word[-1] def _test(verbose=False): import doctest doctest.testmod(verbose=verbose)
stephenj@lords:~$ python scramble.py --test --verbose Trying: scramble('a') Expecting: 'a' ok Trying: scramble('an') Expecting: 'an' ok Trying: scramble('the') Expecting: 'the' ok Trying: scramble('cart') in ['cart', 'crat'] Expecting: True ok 5 items had no tests: __main__ __main__._main __main__._profile_main __main__._test __main__.really_blurt 1 items passed all tests: 4 tests in __main__.scramble 4 tests in 6 items. 4 passed and 0 failed. Test passed. stephenj@lords:~$
Now I'm a real  boy  Unix filter def _blurt(s, f): pass def _main(filename=None): f = sys.stdin if filename: try: f = file(filename) except Exception, ex: print &quot;Couldn't open file %s: %s&quot; % (filename, ex) return 1 while 1: line =  f.readline() if not line: break _blurt(&quot;Original line was: %s&quot; % line) sys.stdout.write(' '.join([scramble(w) for w in line.split()]) + '') return 0 if __name__ == &quot;__main__&quot;: ... if options.verbose: def really_blurt(s, f=()): sys.stderr.write(s % f + '') _blurt = really_blurt ... if len(args) > 0: filename = args[0] _blurt(&quot;filename is %s&quot;, filename) sys.exit(_main(filename))
Dealing with performance anxiety def _profile_main(filename=None): import cProfile, pstats prof = cProfile.Profile() ctx = &quot;&quot;&quot;_main(filename)&quot;&quot;&quot; prof = prof.runctx(ctx, globals(), locals()) stats = pstats.Stats(prof) stats.sort_stats(&quot;cumulative&quot;) stats.print_stats(10) ... if __name__ == &quot;__main__&quot;: ... if options.profile: _profile_main(filename) exit()
Making use of our options stephenj@lords:~$ python scramble.py asdf Couldn't open file asdf: [Errno 2] No such file or directory: 'asdf' stephenj@lords:~$ echo $? 1 stephenj@lords:~$ echo &quot;You should probably be able to understand this&quot; | python scramble.py -v Original line was: You should probably be able to understand this You suhold pbrbolay be able to usedanrntd this stephenj@lords:~$ echo &quot;You should probably be able to understand this&quot; | python scramble.py -P You sluohd pbalbroy be albe to unrdentsad tihs 57 function calls in 0.000 CPU seconds Ordered by: internal time List reduced from 12 to 10 due to restriction <10> ncalls  tottime  percall  cumtime  percall filename:lineno(function) 5  0.000  0.000  0.000  0.000 /usr/lib/python2.5/random.py:250(shuffle) 8  0.000  0.000  0.000  0.000 scramble.py:16(scramble) 1  0.000  0.000  0.000  0.000 scramble.py:59(_main) 1  0.000  0.000  0.000  0.000 {method 'write' of 'file' objects} 17  0.000  0.000  0.000  0.000 {method 'random' of '_random.Random' objects} 2  0.000  0.000  0.000  0.000 {method 'readline' of 'file' objects} 13  0.000  0.000  0.000  0.000 {len} 6  0.000  0.000  0.000  0.000 {method 'join' of 'str' objects} 1  0.000  0.000  0.000  0.000 <string>:1(<module>) 1  0.000  0.000  0.000  0.000 {method 'split' of 'str' objects}
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys from optparse import OptionParser def _test(verbose=None): import doctest doctest.testmod(verbose=verbose) def _profile_main( filename=None ): import cProfile, pstats prof = cProfile.Profile() ctx = &quot;&quot;&quot;_main(filename)&quot;&quot;&quot; prof = prof.runctx(ctx, globals(), locals()) stats = pstats.Stats(prof) stats.sort_stats(&quot;time&quot;) stats.print_stats(10) def _blurt(s, f): pass def _main(filename=None): # YOUR CODE HERE return 0 if __name__ == &quot;__main__&quot;: usage = &quot;usage: %prog [options]  [filename] &quot; parser = OptionParser(usage=usage) parser.add_option('--profile', '-P', help  = &quot;Print out profiling stats&quot;, action  = 'store_true') parser.add_option('--test', '-t', help  ='Run doctests', action = 'store_true') parser.add_option('--verbose', '-v', help  ='print debugging output', action = 'store_true') (options, args) = parser.parse_args() if options.verbose: def really_blurt(s, f=()): sys.stderr.write(s % f + '') _blurt = really_blurt # Assign non-flag arguments here. filename = args[0] if options.profile: _profile_main( filename ) exit() if options.test: _test(verbose=options.verbose) exit() sys.exit(_main( filename ))
Original inspiration Guido's post and subsequent commentary http://www.artima.com/forums/flat.jsp?forum=106&thread=4829 Google app engine help http://code.google.com/appengine/kb/commontasks.html#profiling The scrambled text meme http://www.snopes.com/language/apocryph/cambridge.asp

Más contenido relacionado

La actualidad más candente

python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slidejonycse
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basicsLuigi De Russis
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?Nikita Popov
 
PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)Nikita Popov
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parserkamaelian
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6garux
 
Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic OperationsWai Nwe Tun
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteGiordano Scalzo
 
Top 10 pieges php afup limoges
Top 10 pieges php   afup limogesTop 10 pieges php   afup limoges
Top 10 pieges php afup limogesDamien Seguy
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2RajKumar Rampelli
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimizationg3_nittala
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Contextlichtkind
 
PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)Nikita Popov
 
The Perl6 Type System
The Perl6 Type SystemThe Perl6 Type System
The Perl6 Type Systemabrummett
 
Down the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoDown the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoRemco Wendt
 

La actualidad más candente (20)

python beginner talk slide
python beginner talk slidepython beginner talk slide
python beginner talk slide
 
AmI 2016 - Python basics
AmI 2016 - Python basicsAmI 2016 - Python basics
AmI 2016 - Python basics
 
P3 2018 python_regexes
P3 2018 python_regexesP3 2018 python_regexes
P3 2018 python_regexes
 
Five
FiveFive
Five
 
Don't do this
Don't do thisDon't do this
Don't do this
 
PHP 7 – What changed internally?
PHP 7 – What changed internally?PHP 7 – What changed internally?
PHP 7 – What changed internally?
 
PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)PHP 7 – What changed internally? (Forum PHP 2015)
PHP 7 – What changed internally? (Forum PHP 2015)
 
SWP - A Generic Language Parser
SWP - A Generic Language ParserSWP - A Generic Language Parser
SWP - A Generic Language Parser
 
Introdução ao Perl 6
Introdução ao Perl 6Introdução ao Perl 6
Introdução ao Perl 6
 
Matlab and Python: Basic Operations
Matlab and Python: Basic OperationsMatlab and Python: Basic Operations
Matlab and Python: Basic Operations
 
Bdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infiniteBdd: Tdd and beyond the infinite
Bdd: Tdd and beyond the infinite
 
Top 10 pieges php afup limoges
Top 10 pieges php   afup limogesTop 10 pieges php   afup limoges
Top 10 pieges php afup limoges
 
Perl 6 by example
Perl 6 by examplePerl 6 by example
Perl 6 by example
 
Learn python - for beginners - part-2
Learn python - for beginners - part-2Learn python - for beginners - part-2
Learn python - for beginners - part-2
 
Profiling and optimization
Profiling and optimizationProfiling and optimization
Profiling and optimization
 
A tour of Python
A tour of PythonA tour of Python
A tour of Python
 
Perl 6 in Context
Perl 6 in ContextPerl 6 in Context
Perl 6 in Context
 
PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)PHP 7 – What changed internally? (PHP Barcelona 2015)
PHP 7 – What changed internally? (PHP Barcelona 2015)
 
The Perl6 Type System
The Perl6 Type SystemThe Perl6 Type System
The Perl6 Type System
 
Down the rabbit hole, profiling in Django
Down the rabbit hole, profiling in DjangoDown the rabbit hole, profiling in Django
Down the rabbit hole, profiling in Django
 

Similar a The bones of a nice Python script

Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Parkpointstechgeeks
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fuclimatewarrior
 
Scientific Computing with Python Webinar --- May 22, 2009
Scientific Computing with Python Webinar --- May 22, 2009Scientific Computing with Python Webinar --- May 22, 2009
Scientific Computing with Python Webinar --- May 22, 2009Enthought, Inc.
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick offAndrea Gangemi
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonPython Ireland
 
Why Python by Marilyn Davis, Marakana
Why Python by Marilyn Davis, MarakanaWhy Python by Marilyn Davis, Marakana
Why Python by Marilyn Davis, MarakanaMarko Gargenta
 
How Xslate Works
How Xslate WorksHow Xslate Works
How Xslate WorksGoro Fuji
 
Writing Apps the Google-y Way
Writing Apps the Google-y WayWriting Apps the Google-y Way
Writing Apps the Google-y WayPamela Fox
 
Python 3000
Python 3000Python 3000
Python 3000Bob Chao
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With PhpJeremy Coates
 
Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Pamela Fox
 
Characterset
CharactersetCharacterset
CharactersetHari K T
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationPrestaShop
 

Similar a The bones of a nice Python script (20)

Python - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave ParkPython - Getting to the Essence - Points.com - Dave Park
Python - Getting to the Essence - Points.com - Dave Park
 
Python quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung FuPython quickstart for programmers: Python Kung Fu
Python quickstart for programmers: Python Kung Fu
 
Scientific Computing with Python Webinar --- May 22, 2009
Scientific Computing with Python Webinar --- May 22, 2009Scientific Computing with Python Webinar --- May 22, 2009
Scientific Computing with Python Webinar --- May 22, 2009
 
Perl Presentation
Perl PresentationPerl Presentation
Perl Presentation
 
C to perl binding
C to perl bindingC to perl binding
C to perl binding
 
Prototype js
Prototype jsPrototype js
Prototype js
 
Python scripting kick off
Python scripting kick offPython scripting kick off
Python scripting kick off
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Object Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in PythonObject Orientation vs. Functional Programming in Python
Object Orientation vs. Functional Programming in Python
 
Why Python by Marilyn Davis, Marakana
Why Python by Marilyn Davis, MarakanaWhy Python by Marilyn Davis, Marakana
Why Python by Marilyn Davis, Marakana
 
How Xslate Works
How Xslate WorksHow Xslate Works
How Xslate Works
 
Python 3000
Python 3000Python 3000
Python 3000
 
Writing Apps the Google-y Way
Writing Apps the Google-y WayWriting Apps the Google-y Way
Writing Apps the Google-y Way
 
Python 3000
Python 3000Python 3000
Python 3000
 
Auxiliary
AuxiliaryAuxiliary
Auxiliary
 
Exploiting Php With Php
Exploiting Php With PhpExploiting Php With Php
Exploiting Php With Php
 
Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)Writing Apps the Google-y Way (Brisbane)
Writing Apps the Google-y Way (Brisbane)
 
Characterset
CharactersetCharacterset
Characterset
 
Good practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimizationGood practices for PrestaShop code security and optimization
Good practices for PrestaShop code security and optimization
 
python codes
python codespython codes
python codes
 

Último

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024BookNet Canada
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Strongerpanagenda
 
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
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersNicole Novielli
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsRavi Sanghani
 
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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI AgeCprime
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch TuesdayIvanti
 
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
 
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
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsNathaniel Shimoni
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...panagenda
 
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
 
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
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...AliaaTarek5
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfLoriGlavin3
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxLoriGlavin3
 
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
 
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
 

Último (20)

New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
New from BookNet Canada for 2024: Loan Stars - Tech Forum 2024
 
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better StrongerModern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
Modern Roaming for Notes and Nomad – Cheaper Faster Better Stronger
 
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.
 
A Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software DevelopersA Journey Into the Emotions of Software Developers
A Journey Into the Emotions of Software Developers
 
Potential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and InsightsPotential of AI (Generative AI) in Business: Learnings and Insights
Potential of AI (Generative AI) in Business: Learnings and Insights
 
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
 
A Framework for Development in the AI Age
A Framework for Development in the AI AgeA Framework for Development in the AI Age
A Framework for Development in the AI Age
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
2024 April Patch Tuesday
2024 April Patch Tuesday2024 April Patch Tuesday
2024 April Patch Tuesday
 
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
 
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...
 
Time Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directionsTime Series Foundation Models - current state and future directions
Time Series Foundation Models - current state and future directions
 
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
Why device, WIFI, and ISP insights are crucial to supporting remote Microsoft...
 
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
 
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
 
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
(How to Program) Paul Deitel, Harvey Deitel-Java How to Program, Early Object...
 
Moving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdfMoving Beyond Passwords: FIDO Paris Seminar.pdf
Moving Beyond Passwords: FIDO Paris Seminar.pdf
 
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptxMerck Moving Beyond Passwords: FIDO Paris Seminar.pptx
Merck Moving Beyond Passwords: FIDO Paris Seminar.pptx
 
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
 
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...
 

The bones of a nice Python script

  • 1. Developing a nice template for new scripts
  • 2. #!/usr/bin/python import sys import random def scramble(word): if len(word) < 4: return word innards = list(word[1:-1]) random.shuffle(innards) return word[0] + ''.join(innards) + word[-1] while 1: line = sys.stdin.readline() if not line: break sys.stdout.write(' '.join([scramble(w) for w in line.split()]) + '') In the beginning
  • 3. Adding basic niceties #!/usr/bin/ env python # -*- coding: utf-8 -*- import sys import random def scramble(word): if len(word) < 4: return word innards = list(word[1:-1]) random.shuffle(innards) return word[0] + ''.join(innards) + word[-1] def _main(): while 1: line = sys.stdin.readline() if not line: break sys.stdout.write(' '.join([scramble(w) for w in line.split()]) + '') return 0 if __name__ == &quot;__main__&quot;: sys.exit(_main())
  • 4. stephenj@lords:~$ python Python 2.5.2 (r252:60911, Oct 5 2008, 19:24:49) [GCC 4.3.2] on linux2 Type &quot;help&quot;, &quot;copyright&quot;, &quot;credits&quot; or &quot;license&quot; for more information. >>> import scramble >>> scramble.scramble('scramble') 'srlacmbe' >>>
  • 5. from optparse import OptionParser ... def _main(filename=None): ... if __name__ == &quot;__main__&quot;: usage = &quot;usage: %prog [options] [filename]&quot; parser = OptionParser(usage=usage) parser.add_option('--profile', '-P', help = &quot;Print out profiling stats&quot;, action = 'store_true') parser.add_option('--test', '-t', help ='Run doctests', action = 'store_true') parser.add_option('--verbose', '-v', help ='print debugging output', action = 'store_true') (options, args) = parser.parse_args() # Assign non-flag arguments here. filename = None if len(args) > 0: filename = args[0]
  • 6. stephenj@lords:~$ python scramble.py -h Usage: scramble.py [options] [filename] Options: -h, --help show this help message and exit -P, --profile Print out profiling stats -t, --test Run doctests -v, --verbose print debugging output
  • 7. Tests are good def scramble(word): &quot;&quot;&quot; Returns a scrambled version if it is longer than 3 chars. Scrambling preserves the first and last characters. >>> scramble('a') 'a' >>> scramble('an') 'an' >>> scramble('the') 'the' >>> scramble('cart') in ['cart', 'crat'] True &quot;&quot;&quot; if len(word) < 4: return word innards = list(word[1:-1]) random.shuffle(innards) return word[0] + ''.join(innards) + word[-1] def _test(verbose=False): import doctest doctest.testmod(verbose=verbose)
  • 8. stephenj@lords:~$ python scramble.py --test --verbose Trying: scramble('a') Expecting: 'a' ok Trying: scramble('an') Expecting: 'an' ok Trying: scramble('the') Expecting: 'the' ok Trying: scramble('cart') in ['cart', 'crat'] Expecting: True ok 5 items had no tests: __main__ __main__._main __main__._profile_main __main__._test __main__.really_blurt 1 items passed all tests: 4 tests in __main__.scramble 4 tests in 6 items. 4 passed and 0 failed. Test passed. stephenj@lords:~$
  • 9. Now I'm a real boy Unix filter def _blurt(s, f): pass def _main(filename=None): f = sys.stdin if filename: try: f = file(filename) except Exception, ex: print &quot;Couldn't open file %s: %s&quot; % (filename, ex) return 1 while 1: line = f.readline() if not line: break _blurt(&quot;Original line was: %s&quot; % line) sys.stdout.write(' '.join([scramble(w) for w in line.split()]) + '') return 0 if __name__ == &quot;__main__&quot;: ... if options.verbose: def really_blurt(s, f=()): sys.stderr.write(s % f + '') _blurt = really_blurt ... if len(args) > 0: filename = args[0] _blurt(&quot;filename is %s&quot;, filename) sys.exit(_main(filename))
  • 10. Dealing with performance anxiety def _profile_main(filename=None): import cProfile, pstats prof = cProfile.Profile() ctx = &quot;&quot;&quot;_main(filename)&quot;&quot;&quot; prof = prof.runctx(ctx, globals(), locals()) stats = pstats.Stats(prof) stats.sort_stats(&quot;cumulative&quot;) stats.print_stats(10) ... if __name__ == &quot;__main__&quot;: ... if options.profile: _profile_main(filename) exit()
  • 11. Making use of our options stephenj@lords:~$ python scramble.py asdf Couldn't open file asdf: [Errno 2] No such file or directory: 'asdf' stephenj@lords:~$ echo $? 1 stephenj@lords:~$ echo &quot;You should probably be able to understand this&quot; | python scramble.py -v Original line was: You should probably be able to understand this You suhold pbrbolay be able to usedanrntd this stephenj@lords:~$ echo &quot;You should probably be able to understand this&quot; | python scramble.py -P You sluohd pbalbroy be albe to unrdentsad tihs 57 function calls in 0.000 CPU seconds Ordered by: internal time List reduced from 12 to 10 due to restriction <10> ncalls tottime percall cumtime percall filename:lineno(function) 5 0.000 0.000 0.000 0.000 /usr/lib/python2.5/random.py:250(shuffle) 8 0.000 0.000 0.000 0.000 scramble.py:16(scramble) 1 0.000 0.000 0.000 0.000 scramble.py:59(_main) 1 0.000 0.000 0.000 0.000 {method 'write' of 'file' objects} 17 0.000 0.000 0.000 0.000 {method 'random' of '_random.Random' objects} 2 0.000 0.000 0.000 0.000 {method 'readline' of 'file' objects} 13 0.000 0.000 0.000 0.000 {len} 6 0.000 0.000 0.000 0.000 {method 'join' of 'str' objects} 1 0.000 0.000 0.000 0.000 <string>:1(<module>) 1 0.000 0.000 0.000 0.000 {method 'split' of 'str' objects}
  • 12. #!/usr/bin/env python # -*- coding: utf-8 -*- import sys from optparse import OptionParser def _test(verbose=None): import doctest doctest.testmod(verbose=verbose) def _profile_main( filename=None ): import cProfile, pstats prof = cProfile.Profile() ctx = &quot;&quot;&quot;_main(filename)&quot;&quot;&quot; prof = prof.runctx(ctx, globals(), locals()) stats = pstats.Stats(prof) stats.sort_stats(&quot;time&quot;) stats.print_stats(10) def _blurt(s, f): pass def _main(filename=None): # YOUR CODE HERE return 0 if __name__ == &quot;__main__&quot;: usage = &quot;usage: %prog [options] [filename] &quot; parser = OptionParser(usage=usage) parser.add_option('--profile', '-P', help = &quot;Print out profiling stats&quot;, action = 'store_true') parser.add_option('--test', '-t', help ='Run doctests', action = 'store_true') parser.add_option('--verbose', '-v', help ='print debugging output', action = 'store_true') (options, args) = parser.parse_args() if options.verbose: def really_blurt(s, f=()): sys.stderr.write(s % f + '') _blurt = really_blurt # Assign non-flag arguments here. filename = args[0] if options.profile: _profile_main( filename ) exit() if options.test: _test(verbose=options.verbose) exit() sys.exit(_main( filename ))
  • 13. Original inspiration Guido's post and subsequent commentary http://www.artima.com/forums/flat.jsp?forum=106&thread=4829 Google app engine help http://code.google.com/appengine/kb/commontasks.html#profiling The scrambled text meme http://www.snopes.com/language/apocryph/cambridge.asp