【问题标题】:How to write an ipython alias which executes in python instead of shell?如何编写在 python 而不是 shell 中执行的 ipython 别名?
【发布时间】:2015-07-26 05:40:03
【问题描述】:

我们可以在 ipython 中使用 %alias 魔术函数定义一个 alias,如下所示:

>>> d
NameError: name 'd' is not defined
>>> %alias d date
>>> d
Fri May 15 00:12:20 AEST 2015

当您在 ipython 中键入 d 时,这将转义到 shell 命令 date

但我想定义一个别名来在当前解释器范围内执行一些 python 代码,而不是 shell 命令。那可能吗?这种别名怎么做?

我经常在交互式解释器中工作,这可以节省很多我发现自己经常重复的命令,还可以防止一些常见的拼写错误。

【问题讨论】:

    标签: python macros ipython alias ipython-magic


    【解决方案1】:

    执行此操作的正常方法是简单地编写一个带有def 的python 函数。但是如果你想给一个statement 起别名,而不是一个函数调用,那么它实际上有点棘手。

    您可以通过编写自定义magic 函数来实现此目的。这是一个示例,它有效地将 REPL 中的 import 语句别名为 get

    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)
    

    现在可以执行别名为import 语句的get 语句。

    演示:

    In [1]: get json
    --> import json
    
    In [2]: json.loads
    Out[2]: <function json.loads>
    
    In [3]: get potato
    --> import potato
    ---------------------------------------------------------------------------
    ImportError                               Traceback (most recent call last)
    <string> in <module>()
    
    ImportError: No module named potato
    
    In [4]: 
    

    当然,这可以扩展到任意 python 代码和optional arguments are supported aswell

    【讨论】:

      【解决方案2】:

      我不知道 IPython 什么时候提供宏。现在你可以简单地这样做了:

      ipy = get_ipython()
      ipy.define_macro('d', 'date')
      

      您可以将此代码放入位于~/.ipython/profile_default/startup/ 的任何文件中,然后启动IPython 时该宏将自动可用。

      但是,宏不接受参数。所以请在选择定义宏之前记住这一点。

      【讨论】:

        猜你喜欢
        • 2018-02-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-01-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多