Presentation for Quipper Alumni Meetup held in 2019.
`shell invocation` inPython 2@manicmaniac
View Slide
Ryosuke Ito• iOS software engineer• Working for Quipper Ltd. since Apr. 2019• Loves Python@manicmaniac
Python 2
EOL of Python 22020-01-01 00:00:00Only 15 days left!
Shell invocation
In Rubyputs `date`
In Perlprint `date`
In Python 2.7import subprocessprint subprocess.check_output([‘date’]),
In Python <= 2.6import subprocessprocess = subprocess.Popen(['date'], stdout=subprocess.PIPE),stdout, _ = process.communicate()print stdout,
How can I `date`?
Backquotes inPython 2`date` == repr(date) == date.__repr__()
Naive implementationimport subprocessclass date(object):def __repr__(self):return subprocess.check_output(‘date’)date = date()print `date`
Using meta classimport subprocessdef 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`
But how about othercommands?
import backquotesprint `date`
How it works?
Preprocessingimport tokenizedef 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, '('),])...
At Runtimeframe = inspect.currentframe().f_backwhile frame.f_code.co_filename.startswith('importlib'):frame = frame.f_backexecfile(source, frame.f_globals, frame.f_locals)
print `date`
Limitations• Doesn’t work on REPL• Doesn’t work on Python 3• Really buggy
Backquotes inPython 3>>> `date`File "", line 1`date`^SyntaxError: invalid syntax
Don’t use backquotes
R.I.P Python 2Thank you for listening!