如何将变量传递给 IPython 中的魔法“运行”函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14409167/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 11:20:20  来源:igfitidea点击:

How to pass a variable to magic ′run′ function in IPython

pythonipythonipython-magic

提问by nadapez

I want to do something like the following:

我想做如下事情:

In[1]: name = 'long_name_to_type_every_now_and_then.py'

In[2]: %run name

but this actually tries to run 'name.py', which is not what I want to do.

但这实际上试图运行'name.py',这不是我想要做的。

Is there a general way to turn variables into strings?

是否有将变量转换为字符串的通用方法?

Something like the following:

类似于以下内容:

In[3]: %run %name%

采纳答案by minrk

IPython expands variables with $name, bash-style. This is true for all magics, not just %run.

IPython 使用$name, bash 风格扩展变量。这适用于所有魔法,而不仅仅是%run.

So you would do:

所以你会这样做:

In [1]: filename = "myscript.py"

In [2]: %run $filename
['myscript.py']

myscript.py contains:

myscript.py 包含:

import sys
print(sys.argv)

Via Python's fancy string formatting, you can even put expressions inside {}:

通过 Python 花哨的字符串格式,您甚至可以将表达式放入{}

In [3]: args = ["arg1", "arg2"]

In [4]: %run $filename {args[0]} {args[1][-2:]}
['myscript.py', 'arg1', 'g2']

回答by David Wolever

Use get_ipython()to get a reference to the current InteractiveShell, then call the magic()method:

使用get_ipython()去的电流的基准InteractiveShell,然后调用magic()方法:

In [1]: ipy = get_ipython()

In [2]: ipy.magic("run foo.py")
ERROR: File `u'foo.py'` not found.

EditSee minrk's answer— that's a much better way to do it.

编辑请参阅minrk 的回答——这是一个更好的方法。

回答by Emmett Butler

It seems this is impossible with the built-in %runmagic function. Your question led me down a rabbit hole, though, and I wanted to see how easy it would be to do something similar. At the end, it seems somewhat pointless to go to all this effort to create another magic function that just uses execfile(). Maybe this will be of some use to someone, somewhere.

对于内置的%run魔法功能,这似乎是不可能的。不过,你的问题让我陷入了困境,我想看看做类似的事情有多容易。最后,为了创建另一个仅使用execfile(). 也许这对某人,某处会有一些用处。

# custom_magics.py
from IPython.core.magic import register_line_magic, magics_class, line_magic, Magics

@magics_class
class StatefulMagics(Magics):
    def __init__(self, shell, data):
        super(StatefulMagics, self).__init__(shell)
        self.namespace = data

    @line_magic
    def my_run(self, line):
        if line[0] != "%":
            return "Not a variable in namespace"
        else:
            filename = self.namespace[line[1:]].split('.')[0]
            filename += ".py"
            execfile(filename)
        return line

class Macro(object):
    def __init__(self, name, value):
        self.name = name
        self._value = value
        ip = get_ipython()
        magics = StatefulMagics(ip, {name: value})
        ip.register_magics(magics)

    def value(self):
        return self._value

    def __repr__(self):
        return self.name

Using this pair of classes, (and given a python script tester.py) it's possible to create and use a "macro" variable with the newly created "my_run" magic function like so:

使用这对类(并给定一个 python 脚本tester.py),可以使用新创建的“my_run”魔术函数创建和使用“宏”变量,如下所示:

In [1]: from custom_magics import Macro

In [2]: Macro("somename", "tester.py")
Out[2]: somename

In [3]: %my_run %somename
I'm the test file and I'm running!
Out[3]: u'%somename'

Yes, this is a huge and probably wasteful hack. In that vein, I wonder if there's a way to have the name bound to the Macro object be used as the macro's actual name. Will look into that.

是的,这是一个巨大的,可能是浪费的黑客攻击。在这种情况下,我想知道是否有办法将绑定到 Macro 对象的名称用作宏的实际名称。会调查那个。

回答by Bar?? Deniz Sa?lam

In case there might be space in argument, e.g. filename, it is better to use this:

如果参数中可能有空格,例如文件名,最好使用这个:

%run "$filename"