在 jupyter/ipython notebook 中将命令行参数传递给 argv [英] Passing command line arguments to argv in jupyter/ipython notebook

查看:72
本文介绍了在 jupyter/ipython notebook 中将命令行参数传递给 argv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否可以在 jupyter/ipython 笔记本中使用命令行参数填充 sys.argv(或其他结构),类似于通过 python 脚本完成的方式.

I'm wondering if it's possible to populate sys.argv (or some other structure) with command line arguments in a jupyter/ipython notebook, similar to how it's done through a python script.

例如,如果我要按如下方式运行 python 脚本:

For instance, if I were to run a python script as follows:

python test.py 错误

然后 sys.argv 将包含参数 False.但是如果我以类似的方式运行 jupyter notebook:

Then sys.argv would contain the argument False. But if I run a jupyter notebook in a similar manner:

jupyter notebook test.ipynb False

然后命令行参数丢失.有没有办法从笔记本内部访问这个参数?

Then the command line argument gets lost. Is there any way to access this argument from within the notebook itself?

推荐答案

环顾四周后,我发现非常麻烦的自定义库,但我用几行代码解决了它,我认为这些代码非常巧妙.我使用 nbconvert 最终得到一个 html 报告作为输出,其中包含笔记本中的所有图形和降价,但像往常一样通过最小的 python 包装器接受命令行参数:

After a lot of looking around I found very cumbersome, custom libraries, but solved it with a few lines of code which I thought was pretty slick. I used nbconvert to end up with an html report as output that contains all graphics and markdown from the notebook, but accepts command line parameters just as always through a minimal python wrapper:

python 文件 test_args.py(正常使用命令行参数):

The python file test_args.py (which takes command line params as normal):

import sys,os
IPYNB_FILENAME = 'test_argv.ipynb'
CONFIG_FILENAME = '.config_ipynb'

def main(argv):
    with open(CONFIG_FILENAME,'w') as f:
        f.write(' '.join(argv))
    os.system('jupyter nbconvert --execute {:s} --to html'.format(IPYNB_FILENAME))
    return None

if __name__ == '__main__':
    main(sys.argv)

笔记本包含:

import sys,os,argparse
from IPython.display import HTML
CONFIG_FILE = '.config_ipynb'
if os.path.isfile(CONFIG_FILE):
    with open(CONFIG_FILE) as f:
        sys.argv = f.read().split()
else:
    sys.argv = ['test_args.py', 'input_file', '--int_param', '12']

parser = argparse.ArgumentParser()
parser.add_argument("input_file",help="Input image, directory, or npy.")
parser.add_argument("--int_param", type=int, default=4, help="an optional integer parameter.")
args = parser.parse_args()
p = args.int_param
print(args.input_file,p)

我可以像往常一样运行带有解析参数的python笔记本:

and I can run the python notebook with arguments parsed as usual:

python test_args.py my_input_file --int_param 12

我倾向于将带有 argparse 调用的块粘贴到 python 包装器中,以便 python 脚本捕获命令行错误并且 -h 正常工作.

I tend to paste the block with argparse calls into the python wrapper so that command line errors are caught by the python script and -h works properly.

这篇关于在 jupyter/ipython notebook 中将命令行参数传递给 argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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