-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.html
More file actions
1574 lines (1129 loc) · 35 KB
/
Copy pathindex.html
File metadata and controls
1574 lines (1129 loc) · 35 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html>
<head>
<title>Building useful project utils in Python</title>
<meta charset="utf-8">
<style>
@page {
size: 1210px 681px;
margin: 0;
}
@media print {
.remark-slide-scaler {
width: 100% !important;
height: 100% !important;
transform: scale(1) !important;
top: 0 !important;
left: 0 !important;
}
}
@font-face {
font-family: 'Yanone Kaffeesatz';
font-style: normal;
font-weight: 400;
src:
local('Yanone Kaffeesatz Regular'),
local('YanoneKaffeesatz-Regular'),
url('YanoneKaffeesatz-Regular.ttf') format('truetype');
}
@font-face {
font-family: 'Droid Serif';
font-style: italic;
font-weight: 400;
src:
local('Droid Serif Italic'),
local('DroidSerif-Italic'),
url('DroidSerif-Italic.ttf') format('truetype');
}
@font-face {
font-family: 'Droid Serif';
font-style: normal;
font-weight: 400;
src:
local('Droid Serif Regular'),
local('DroidSerif-Regular'),
url('DroidSerif-Regular.ttf') format('truetype');
}
@font-face {
font-family: 'Droid Serif';
font-style: normal;
font-weight: 700;
src:
local('Droid Serif Bold'),
local('DroidSerif-Bold'),
url('DroidSerif-Bold.ttf') format('truetype');
}
@font-face {
font-family: 'Ubuntu Mono';
font-style: italic;
font-weight: 400;
src:
local('Ubuntu Mono Italic'),
local('UbuntuMono-Italic'),
url('UbuntuMono-Italic.ttf') format('truetype');
}
@font-face {
font-family: 'Ubuntu Mono';
font-style: normal;
font-weight: 400;
src:
local('Ubuntu Mono'),
local('UbuntuMono-Regular'),
url('UbuntuMono-Regular.ttf') format('truetype');
}
@font-face {
font-family: 'Ubuntu Mono';
font-style: normal;
font-weight: 700;
src:
local('Ubuntu Mono Bold'),
local('UbuntuMono-Bold'),
url('UbuntuMono-Bold.ttf') format('truetype');
}
body { font-family: 'Droid Serif'; }
h1, h2, h3 {
font-family: 'Yanone Kaffeesatz';
font-weight: normal;
}
a {
color: #F92672;
text-decoration: none;
}
li {
padding: 2px;
}
blockquote {
padding: 20px;
background: rgba(240, 240, 240, 0.5);
}
p {
margin-bottom: 0;
}
pre {
margin-top: 0;
}
tt, code {
font-family: 'Ubuntu Mono';
}
.ordinal {
vertical-align: super;
font-size: small;
}
.remark-code, .remark-inline-code {
font-family: 'Ubuntu Mono';
background: rgba(240, 240, 240, 0.5) !important;
}
.remark-inline-code {
font-family: 'Ubuntu Mono';
background: rgba(240, 240, 240, 0.90);
padding: 2px 5px;
}
.remark-slide-content {
background:
linear-gradient(
rgba(255, 255, 255, 0.75),
rgba(255, 255, 255, 0.25)
),
url('images/light_bg.jpg'),
#ffffff;
background-size: cover;
}
.inverse-empty {
background:
url('images/space_bg.jpg'),
#272822;
background-size: cover;
color: #777872;
}
.inverse {
background:
linear-gradient(
rgba(0, 0, 0, 0.5),
rgba(0, 0, 0, 0.5)
),
url('images/space_bg.jpg'),
#272822;
background-size: cover;
color: #777872;
text-shadow: 0 0 20px #333;
}
.inverse h1, .inverse h2 {
color: #f3f3f3;
line-height: 0.8em;
}
.column:first-of-type { float: left; }
.column { float: right; }
.split-50 .column { width: 48%; }
.split-33 .column:first-of-type { width: 32%; }
.split-33 .column { width: 64%; }
.split-72 .column:first-of-type { width: 72%; }
.split-72 .column { width: 27%; }
</style>
</head>
<body>
<textarea id="source">
class: inverse-empty
---
class: center, middle, inverse
# Building useful project utils in Python
## From spaghetti shell scripts to presentable Python
Johan Herland<br />
<a href="https://twitter.com/jherland">@jherland</a><br />
<<a href="mailto:jherland@cisco.com">jherland@cisco.com</a>><br />
<<a href="mailto:johan@herland.net">johan@herland.net</a>>
???
Who am I?
- Software Engineer at Cisco Systems Norway, developing videoconferencing systems
- Work on:
- Some applicaton-level programming
- More underlying platform work
- Version control, build systems, developer tools
---
# Prerequisites
- Basic familiarity with Unix shell scripting (<code>bash</code>)
- Some familiarity with <code>python3</code> (<code>python2</code> also works, but YMMV)
---
# Outline
- Motivation
- What scripts are we talking about?
- Shell scripts! What are they good for?
- Why is Python better?
- Shell → Python — Tips + Techniques
- Code organization
- Command-line interfaces in Python
- Running other programs from Python
- Manipulating the filesystem from Python
- Writing unit tests in Python
- A controversial take on error handling
- Case study — <code>binst</code>
- A real-world rewrite from Shell to Python
- Adding features that would have been impossible in Shell
- Summary
- Q & A
---
class: center, middle, inverse
# Motivation
---
class: split-50
## What scripts are we talking about?
"The glue that holds your project together"
.column[
### Developer tools
- Wrappers for more complex commands
- Workflow helpers
### Build-time
- Small + simple build systems
- Build system helpers, plug-ins
- Code generators
]
.column[
### Packaging, deployment, release, ...
- Signing images
- Publishing assets
### In production
- Embedded targets
- Inside deployed containers
]
---
class: split-50
## Shell scripts! What are they good for?
.column[
### Pros
- Short and simple stuff
- Straightforward logic
- No data structures
]
--
.column[
### Cons
- Scripts grow, in length and complexity
- Complex logic
- Data structures
- Configurability
- Reusability
- Safety!
]
---
## Why is Python better?
### Showdown! Shell vs. Python
---
class: split-50
## Why is Python better? — Syntax
.column[
### Shell
- Reasonably easy to become productive
- Similar to command-line; skills are transferable
- Complexity → write-only
- Trivial (and necessary) to run other programs
- Many pitfalls, hard to become **safe**
- Many online resources/examples
- **Common practice** != **Best practice**!
- **Pro Tip**: Use <a href="https://www.shellcheck.net">**ShellCheck**</a>
to catch common shell scripting errors!
```bash
filename="My favourite quotations.txt"
touch $filename
```
]
--
.column[
### Python
- Simple and beginner-friendly syntax
- Considered one of the more readable languages
- Not as trivial to run other programs
- Fewer pitfalls than shell.
- Lots of literature and resources.
- Harder to come across "dangerous" examples
]
---
class: split-50
## Why is Python better? — Data structures and types
.column[
### Shell
- Everything is a string
- Whitespace in values often cause problems, and must be handled carefully
- Some support for integer arithmetic
- Some support for arrays
<blockquote>
<small>«Unlike many other programming languages, Bash does not segregate its variables by "type." Essentially, Bash variables are character strings, but, depending on context, Bash permits arithmetic operations and comparisons on variables. The determining factor is whether the value of a variable contains only digits.»</small><br />
<br />
— <a href="https://tldp.org/LDP/abs/html/untyped.html">Advanced Bash-Scripting Guide</a>
</blockquote>
]
--
.column[
### Python
- Dynamically (but strongly) typed
- Built-in types:
- Numerics — <code>int</code>, <code>float</code>, <code>complex</code>
- Sequences — <code>list</code>, <code>tuple</code>, <code>range</code>
- Text and binary data — <code>str</code>, <code>bytes</code>, ...
- Sets — <code>set</code>, ...
- Mappings — <code>dict</code>
- Others:
- Modules
- Classes and Class instances
- Functions and Methods
- Iterators and Generators
- Exceptions
- ...
]
---
class: split-50
## Why is Python better? — Modularity
.column[
### Shell
*Within* files: functions
- (sometimes non-obvious behavior, though, e.g. variables have global scope by default)
*Between* files: access in two ways:
1. Direct call (*think:* run as subprocess)
2. Use <code>source</code><br />
(*think:* <code>#include</code> — no namespaces!)
However, a script cannot easily figure out if it has been *called* or *sourced*, so scripts are typically **either** written for immediate usage **or** a as *bag of functions* reusable by sourcing (but does nothing when called).
]
--
.column[
### Python
*Within* files: functions, classes, data, ...
*Between* files: access in two ways:
1. <code>import</code>
2. Call via <code>subprocess</code>
Modules with <code>\_\_main\_\_</code> guards allows **both** for importability, and for immediate usage!
]
---
class: split-50
## Why is Python better? — Modularity (cont.)
.column[
<tt>foo.sh</tt>:
```bash
#!/bin/sh
echo "This is always run"
foo() {
echo "This is foo"
}
```
<tt>bar.sh</tt>:
```bash
#!/bin/sh
source foo.sh
foo
```
]
--
.column[
<tt>foo.py</tt>:
```python
#!/usr/bin/env python3
print("This is always run")
def foo():
print('This is foo')
if __name__ == '__main__':
print("Skipped when this file is imported")
```
<tt>bar.py</tt>:
```python
#!/usr/bin/env python3
import foo
foo.foo()
```
]
---
class: split-50
## Why is Python better? — Tools & Libraries
.column[
### Shell
- Language itself is very minimal
- Use system binaries from Unix ecosystem to do heavy lifting
]
--
.column[
### Python
- Very rich stdlib — can do most things "within" the language
- Lots more 3<span class="ordinal">rd</span>-party modules available (e.g. Python Package Index)
- Use <code>subprocess</code> module to call out to other binaries
]
---
class: center, middle, inverse
# Shell → Python
## Tips + Techniques
---
## Code organization
- Start by simply transcribing your shell script into Python!
- One statement after another
- No change in structure
- Everything is run from top to bottom
--
- Refactor code into functions, classes, data structures, ...
- Incrementally improve the structure of your script
--
- Add the <code>\_\_main\_\_</code> guard
- Makes the functions/classes/data reusable from other scripts
--
- Add a <code>main()</code> function
- Common convention in python
- Other scripts can now <code>import</code> + <code>main()</code> instead of <code>subprocess.run()</code>
--
- Split reusable functionality into separate/stand-alone modules
- Add unit tests here to verify API + functionality
---
## Command-line interfaces in Python
### Follow Unix conventions:
- Exit code 0 → success, non-zero → failure
- Default exit code from python is 0
- Uncaught exceptions result in exit code 1
- Use <code>sys.stdin</code>/<code>sys.stdout</code> for default I/O
- <code>print()</code> defaults to <code>sys.stdout</code>
- Log errors to <code>sys.stderr</code>
- The <code>logging</code> module defaults to <code>sys.stderr</code>
- Mandatory command-line args are *positional*
- Optional command-line args use <code>--dashes</code>
--
### Use <code>argparse</code> ↓
---
class: split-72
Using <code>argparse</code>:
.column[
```python
#!/usr/bin/env python3
'''Calculate the square of a given number.'''
import argparse
import sys
def calc(num, exp):
return num ** exp
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'num', type=int,
help='the number to be squared')
parser.add_argument(
'--cube', '-3', action='store_true',
help='calculate the cube (instead of square)')
parser.add_argument(
'--file', '-f', type=argparse.FileType('w'), default=sys.stdout,
help='write result here (stdout by default)')
args = parser.parse_args()
result = calc(args.num, 3 if args.cube else 2)
print(result, file=args.file)
if __name__ == '__main__':
main()
```
]
--
.column[
```python
# <- Module docstring
# (.__doc__ on the module)
# <- Reusable function:
import myscript
myscript.calc(123, 2)
# <- Reuse module docstring
# in usage help text
# <- Positional integer arg
# <- Optional arg, boolean,
# default: False
# <- Optional arg, open file
# <- __main__ guard
```
]
---
```xml
$ ./myscript.py
usage: myscript.py [-h] [--cube] [--file FILE] num
myscript.py: error: the following arguments are required: num
```
--
```xml
$ ./myscript.py -h
usage: myscript.py [-h] [--cube] [--file FILE] num
Calculate the square of a given number.
positional arguments:
num the number to be squared
optional arguments:
-h, --help show this help message and exit
--cube, -3 calculate the cube (instead of square)
--file FILE, -f FILE write result here (stdout by default)
```
--
```xml
$ ./myscript.py 5
25
```
--
```xml
$ ./myscript.py 5 -3
125
```
--
```xml
$ ./myscript.py 10 -3 -f foo
$ cat foo
1000
```
---
## Running other programs from Python — <code>subprocess</code>
### Simple cases
```python
import subprocess
# Prepare command as a list of strings
argv = ['ping', '-c1', 'google.com']
# Run command, get its exit code
exitcode = subprocess.run(argv).returncode
# Run command, raise exception on non-zero exit code
subprocess.run(argv, check=True)
# Run command, raise exception if it fails, capture its output
result = subprocess.run(argv, check=True, capture_output=True)
output, errors = result.stdout, result.stderr
```
--
### More complex cases
See https://docs.python.org/3/library/subprocess.html
---
class: split-50
## Manipulating the filesystem from Python — <code>pathlib</code>
.column[
- Features:
- Creating/moving/removing files and dirs
- Looking for specific (types of) files
- Handling *relative* vs *absolute* paths
- Replaces/supersedes:
- Parts of <code>os.path.\*</code> and elsewhere in <code>os.\*</code>
- <code>fnmatch.fnmatch()</code> and <code>glob.glob()</code>
- https://docs.python.org/3/library/pathlib.html
### Other modules
- <code>os</code> and <code>os.path</code>
- <code>shutil</code>
]
--
.column[
```python
from pathlib import Path
mydir = Path.cwd() / 'mydir'
mydir.mkdir(exist_ok=True)
foo = mydir / 'foo.txt'
if foo.exists():
foo.rename(foo.with_suffix('.backup'))
with foo.open('w') as f:
for path in mydir.iterdir():
print(path.relative_to(mydir), file=f)
for path in mydir.glob('*.backup'):
path.unlink()
```
]
---
class: split-50
## Writing unit tests in Python
.column[
### What to test
- As much as possible
- Certainly reusable functionality
### Available frameworks
- <a href="https://docs.python.org/3/library/doctest.html"><code>doctest</code></a>
- <a href="https://docs.python.org/3/library/unittest.html"><code>unittest</code></a>
- <a href="https://docs.pytest.org/en/latest/"><code>pytest</code></a> (not in the standard library)
- Many others...
]
--
.column[
### Note
This is not a talk on test frameworks or unit testing in general.
For everything but the smallest scripts, put your tests in separate files, or even separate directories, but here we'll look at how you can put small tests in the same file as the rest of the script.
]
---
Remember?
```python
#!/usr/bin/env python3
'''Calculate the square of a given number.'''
import argparse
import sys
def calc(num, exp):
return num ** exp
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
'num', type=int,
help='the number to be squared')
parser.add_argument(
'--cube', '-3', action='store_true',
help='calculate the cube (instead of square)')
parser.add_argument(
'--file', '-f', type=argparse.FileType('w'), default=sys.stdout,
help='write result here (stdout by default)')
args = parser.parse_args()
result = calc(args.num, 3 if args.cube else 2)
print(result, file=args.file)
if __name__ == '__main__':
main()
```
---
class: split-50
## Writing unit tests in Python — <code>doctest</code>
.column[
Ad-hoc testing:
```bash
$ python
Python 3.7.0 (default, Jul 15 2018, 10:44:58)
[...]
>>> import myscript
>>> myscript.calc(3, 2)
9
```
Let's formalize that a bit:
```python
def calc(num, exp):
'''Return 'num' raised to the power of 'exp'.
>>> [calc(0, 2), calc(1, 2), calc(2, 2)]
[0, 1, 4]
>>> [calc(0, 3), calc(1, 3), calc(2, 3)]
[0, 1, 8]
'''
return num ** exp
```
]
--
.column[
Run tests from command-line:
```bash
$ python -m doctest myscript.py -v
Trying:
[calc(0, 2), calc(1, 2), calc(2, 2)]
Expecting:
[0, 1, 4]
ok
Trying:
[calc(0, 3), calc(1, 3), calc(2, 3)]
Expecting:
[0, 1, 8]
ok
2 items had no tests:
myscript
myscript.main
1 items passed all tests:
2 tests in myscript.calc
2 tests in 3 items.
2 passed and 0 failed.
Test passed.
```
Run tests from within the script:
```python
if __name__ == '__main__':
import doctest
doctest.testmod()
```
]
---
class: split-50
## Writing unit tests in Python — <code>unittest</code>
.column[
```python
import unittest
...
class TestSquare(unittest.TestCase):
def test_zero_squared_is_zero(self):
self.assertEqual(0, calc(0, 2))
def test_one_squared_is_one(self):
self.assertEqual(1, calc(1, 2))
def test_two_squared_is_four(self):
self.assertEqual(4, calc(2, 2))
class TestCube(unittest.TestCase):
def test_zero_cubed_is_zero(self):
self.assertEqual(0, calc(0, 3))
def test_one_cubed_is_one(self):
self.assertEqual(1, calc(1, 3))
def test_two_cubed_is_eight(self):
self.assertEqual(8, calc(2, 3))
```
]
--
.column[
Run tests from command-line:
```bash
$ python -m unittest myscript.py
......
-----------------------------------------------------
Ran 6 tests in 0.000s
OK
```
Run tests from within the script:
```python
if __name__ == '__main__':
unittest.main()
```
]
---
class: split-50
## Writing unit tests in Python — <code>pytest</code>
.column[
```python
def test_calc():
vectors = [
(0, 2, 0), (1, 2, 1), (2, 2, 4),
(0, 3, 0), (1, 3, 1), (2, 3, 8),
]
for num, exp, expect in vectors:
assert calc(num, exp) == expect
```