如何在IPython中将变量传递给magic'run'函数 [英] How to pass a variable to magic ´run´ function in IPython

查看:149
本文介绍了如何在IPython中将变量传递给magic'run'函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做类似以下的事情:

I want to do something like the following:

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

In[2]: %run name

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

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

是否有通用的方法来改变变量成串?

Is there a general way to turn variables into strings?

如下所示:

In[3]: %run %name%


推荐答案

IPython使用<$ c扩展变量$ c> $ name ,bash-style。 所有魔法都是如此,而不仅仅是%run

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

所以你会执行:

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

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

myscript.py包含:

myscript.py contains:

import sys
print(sys.argv)

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

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

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

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

这篇关于如何在IPython中将变量传递给magic'run'函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆