macros - How to write an ipython alias which executes in python instead of shell? -
we can define alias in ipython %alias magic function, this:
>>> d nameerror: name 'd' not defined >>> %alias d date >>> d fri may 15 00:12:20 aest 2015 this escapes shell command date when type d ipython.
but want define alias execute python code, in current interpreter scope, rather shell command. possible? how can make kind of alias?
i work in interactive interpreter lot, , save me lot of commands find myself repeating often, , prevent common typos.
the normal way write python function, def. if want alias statement, rather function call, it's bit tricky.
you can achieve writing custom magic function. here example, aliases import statement get, within repl.
from ipython.core.magic_arguments import argument, magic_arguments @magic_arguments() @argument('module') def magic_import(self, arg): code = 'import {}'.format(arg) print('--> {}'.format(code)) self.shell.run_code(code) ip = get_ipython() ip.define_magic('get', magic_import) now possible execute get statements aliased import statements.
demo:
in [1]: json --> import json in [2]: json.loads out[2]: <function json.loads> in [3]: potato --> import potato --------------------------------------------------------------------------- importerror traceback (most recent call last) <string> in <module>() importerror: no module named potato in [4]: of course, extendible arbitrary python code, , optional arguments supported aswell.
Comments
Post a Comment