$30 off During Our Annual Pro Sale. View Details »

`shell invocation` in Python 2

`shell invocation` in Python 2

Presentation for Quipper Alumni Meetup held in 2019.

Ryosuke Ito

December 16, 2019
Tweet

More Decks by Ryosuke Ito

Other Decks in Programming

Transcript

  1. `shell invocation` in Python 2 @manicmaniac

  2. Ryosuke Ito • iOS software engineer • Working for Quipper

    Ltd. since Apr. 2019 • Loves Python @manicmaniac
  3. Python 2

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

  5. Shell invocation

  6. In Ruby puts `date`

  7. In Perl print `date`

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

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

    stdout, _ = process.communicate() print stdout,
  10. How can I `date`?

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

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

    date = date() print `date`
  13. 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`
  14. But how about other commands?

  15. import backquotes print `date`

  16. None
  17. How it works?

  18. 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, '('), ]) ...
  19. At Runtime frame = inspect.currentframe().f_back while frame.f_code.co_filename.startswith('<frozen importlib'): frame =

    frame.f_back execfile(source, frame.f_globals, frame.f_locals)
  20. print `date`

  21. Limitations • Doesn’t work on REPL • Doesn’t work on

    Python 3 • Really buggy
  22. Backquotes in Python 3 >>> `date` File "<stdin>", line 1

    `date` ^ SyntaxError: invalid syntax
  23. Don’t use backquotes

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