使用jupyter的parser.add_argument和parser.parse_args() [英] parser.add_argument and parser.parse_args() with jupyter

查看:585
本文介绍了使用jupyter的parser.add_argument和parser.parse_args()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用jupyter笔记本运行一些代码,但是从一开始,我就遇到了问题.

I'm trying to run some code with a jupyter notebook, but from the beginning, I have issues.

确实,看来我不能使用以下命令:

Indeed, it looks like I can't use these commands:

parser.add_argument('--lr', default=0.1, type=float, help='learning rate')
parser.add_argument('--resume', '-r', action='store_true', help='resume from checkpoint')

用法:ipykernel_launcher.py [-h] [--lr LR] [--resume] 并且ipykernel_launcher.py给出错误:unrecognized arguments: -f

usage: ipykernel_launcher.py [-h] [--lr LR] [--resume] and ipykernel_launcher.py gives error: unrecognized arguments: -f

并且:

args = parser.parse_args()

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/argparse.py in parse_args(self, args, namespace)
   1750         if argv:
   1751             msg = _('unrecognized arguments: %s')
-> 1752             self.error(msg % ' '.join(argv))
   1753         return args
   1754 

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/argparse.py in error(self, message)
   2499         self.print_usage(_sys.stderr)
   2500         args = {'prog': self.prog, 'message': message}
-> 2501         self.exit(2, _('%(prog)s: error: %(message)s\n') % args)

/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/argparse.py in exit(self, status, message)
   2486         if message:
   2487             self._print_message(message, _sys.stderr)
-> 2488         _sys.exit(status)
   2489 
   2490     def error(self, message):

SystemExit: 2

我已经看到有些人在尝试使用jupyter和arg_parse时已经遇到了这个问题,但是我找不到一个简单的解决方案.

I've seen that some people already had this problem when trying to use jupyter and arg_parse, but I can't find an easy solution.

谢谢您的帮助!

推荐答案

启动空白笔记本并执行

import sys
sys.argv

我知道

['/usr/local/lib/python3.6/dist-packages/ipykernel_launcher.py',
 '-f',
 '/run/user/1000/jupyter/kernel-b2d72478-6aaa-4206-9bf3-38fc1a0fd303.json']

parse_args()使用的sys.argv列表通常来自调用脚本的shell.这是命令行字符串的列表.

parse_args() uses the sys.argv list that 'normally' comes from the shell that's calling your script. It is a list of the commandline strings.

您的脚本看到的sys.argv包含此-f参数,该参数由jupyter创建.

The sys.argv that your script sees includes this -f argument, created by jupyter.

您可以使用parse_known_args(),以便您的解析器不会引发此错误.但这并不能帮助您获取--lr-r参数-因为jupyter's自己的解析器将拒绝它们.

You could use parse_known_args() so that your parser doesn't raise this error. But you that won't help you get --lr or -r arguments - because jupyter's own parser will reject them.

以前的SO问题的实质是您不能向笔记本提供命令行参数.

The essence of the previous SO questions is that you can't provide commandline arguments to a notebooks.

这篇关于使用jupyter的parser.add_argument和parser.parse_args()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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