$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

    View Slide

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

    View Slide

  3. Python 2

    View Slide

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

    View Slide

  5. Shell invocation

    View Slide

  6. In Ruby
    puts `date`

    View Slide

  7. In Perl
    print `date`

    View Slide

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

    View Slide

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

    View Slide

  10. How can I `date`?

    View Slide

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

    View Slide

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

    View Slide

  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`

    View Slide

  14. But how about other
    commands?

    View Slide

  15. import backquotes
    print `date`

    View Slide

  16. View Slide

  17. How it works?

    View Slide

  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, '('),
    ])
    ...

    View Slide

  19. At Runtime
    frame = inspect.currentframe().f_back
    while frame.f_code.co_filename.startswith('importlib'):
    frame = frame.f_back
    execfile(source, frame.f_globals, frame.f_locals)

    View Slide

  20. print `date`

    View Slide

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

    View Slide

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

    View Slide

  23. Don’t use backquotes

    View Slide

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

    View Slide