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

查看:711
本文介绍了在jupyter/ipython笔记本中将命令行参数传递给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 False

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

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笔记本中将命令行参数传递给argv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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