python - 如何向 IPython 的魔法命令添加自定义标志? (.ipy 文件)

标签 python ipython ipython-magic

是否可以向 IPython 的 magic 命令添加自定义标志?更具体地说,我想使用带有自制标志的 %run 命令:

%run script.ipy --flag "option"

并且能够在脚本中使用“选项”。

对于 .py 文件,此处提供了答案:Command Line Arguments In Python

最佳答案

正如评论中所指出的,这个问题不仅仅是关于处理 Python 脚本中的命令行参数。这是关于在通过 %run 运行的 .ipy 文件中处理它们。

如果我创建test.ipy

import sys
print(sys.argv)

并从 shell 运行它,我看到命令行参数:

1223:~/mypy$ python3 test.ipy -test foo
['test.ipy', '-test', 'foo']

但从 ipython session 中,我不知道

In [464]: %run test.ipy --flag test
['/usr/bin/ipython3']

如果我使用 py 名称制作副本

In [468]: %run testipy.py --flag test
['testipy.py', '--flag', 'test']

因此 %run ...ipy 的行为有所不同。这是一个 ipython 问题,而不是一般的 Python 命令行问题。

================

%run 文档有这一点:

There is one special usage for which the text above doesn't apply: if the filename ends with .ipy[nb], the file is run as ipython script, just as if the commands were written on IPython prompt.

在这种情况下,test.ipy 脚本会看到与我键入时相同的 sys.argv:

In [475]: sys.argv
Out[475]: ['/usr/bin/ipython3']

因此,如果我在当前 session 中修改 sys.argv,例如通过附加几个字符串:

In [476]: sys.argv += ['--flag','test']

In [477]: sys.argv
Out[477]: ['/usr/bin/ipython3', '--flag', 'test']

In [479]: %run test.ipy
['/usr/bin/ipython3', '--flag', 'test']

我的 ipy 脚本现在可以看到它们。

这就是答案 - 在使用 %run ...ipy 之前将命令行参数放入 sys.argv 中。

(在使用 argparse 执行高级操作时,我已经对 sys.argv 进行了这种摆弄。)

更多ipython魔法

In [480]: %run??

向我展示了它的文档和代码。因此我可以看到它如何特殊处理 .ipy 文件。因为它很容易找到,所以我不会在这里复制它。

还有另一种解决方案 - 不要尝试对 ipy 文件使用命令行编码风格。

如果我添加一个

print(x)

行到该测试文件,并在我的 Ipython session 中定义了 x,我看到了打印内容。但我将相同的打印内容放入 .py 中,我会得到一个 Nameerror。当他们说 ipy 的运行就像输入一样时,他们是认真的。实际上,运行 ipy 是从剪贴板中 %paste 的替代方案。

关于python - 如何向 IPython 的魔法命令添加自定义标志? (.ipy 文件),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38210320/

相关文章:

python - 错误 : Line magic function

python - IPython %run magic -n 开关不工作

python - 合并具有相同键的两个字典

python - Visual Studio Code - 具有自动完成功能的 Python 交互式数据科学 REPL

ipython 重新加载 ipython_config.py

python - 捕获 IPython 魔法函数的结果

python - Django 将自定义查询集获取到 ListView 中

python - 延迟敌人射击

python - Gensim Word2Vec 模型因增加 epoch 数而变得更糟

python - 在 IPython 中安装新模块