Slide 1

Slide 1 text

`shell invocation` in Python 2 @manicmaniac

Slide 2

Slide 2 text

Ryosuke Ito • iOS software engineer • Working for Quipper Ltd. since Apr. 2019 • Loves Python @manicmaniac

Slide 3

Slide 3 text

Python 2

Slide 4

Slide 4 text

EOL of Python 2 2020-01-01 00:00:00 Only 15 days left!

Slide 5

Slide 5 text

Shell invocation

Slide 6

Slide 6 text

In Ruby puts `date`

Slide 7

Slide 7 text

In Perl print `date`

Slide 8

Slide 8 text

In Python 2.7 import subprocess print subprocess.check_output([‘date’]),

Slide 9

Slide 9 text

In Python <= 2.6 import subprocess process = subprocess.Popen(['date'], stdout=subprocess.PIPE), stdout, _ = process.communicate() print stdout,

Slide 10

Slide 10 text

How can I `date`?

Slide 11

Slide 11 text

Backquotes in Python 2 `date` == repr(date) == date.__repr__()

Slide 12

Slide 12 text

Naive implementation import subprocess class date(object): def __repr__(self): return subprocess.check_output(‘date’) date = date() print `date`

Slide 13

Slide 13 text

Using meta class import subprocess def register_command(name): def __repr__(self): return subprocess.check_output( self.__class__.__name__ ) globals()[name] = type( name, (object,), dict(__repr__=__repr__) )() register_command('date') print `date`

Slide 14

Slide 14 text

But how about other commands?

Slide 15

Slide 15 text

import backquotes print `date`

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

How it works?

Slide 18

Slide 18 text

Preprocessing import tokenize def preprocess(filename, readline): for token in tokenize.generate_tokens(readline): ... if inside_backquotes: tokens.extend([ (tokenize.NAME, 'backquotes'), (tokenize.OP, '.'), (tokenize.NAME, 'shell'), (tokenize.OP, '('), ]) ...

Slide 19

Slide 19 text

At Runtime frame = inspect.currentframe().f_back while frame.f_code.co_filename.startswith('

Slide 20

Slide 20 text

print `date`

Slide 21

Slide 21 text

Limitations • Doesn’t work on REPL • Doesn’t work on Python 3 • Really buggy

Slide 22

Slide 22 text

Backquotes in Python 3 >>> `date` File "", line 1 `date` ^ SyntaxError: invalid syntax

Slide 23

Slide 23 text

Don’t use backquotes

Slide 24

Slide 24 text

R.I.P Python 2 Thank you for listening!