Jupyter Notebook中的Argparse引发TypeError [英] Argparse in Jupyter Notebook throws a TypeError
问题描述
在Jupyter Notebook中使用argparse会引发TypeError.如果我执行与脚本相同的代码,则相同的代码可以正常工作. MWE:
Using argparse in a Jupyter Notebook throws a TypeError. The same code works fine if I execute the same code as a script. MWE:
import argparse
parser = argparse.ArgumentParser(description='Foo')
parser.add_argument('--name', '-n', default='foo', help='foo')
args = parser.parse_args()
结果:
TypeError: 'level' is an invalid keyword argument for this function
推荐答案
Ipython在后台运行一些命令行参数.这会干扰argparse和optparse.
Ipython is running some command-line arguments in the background. This interfers with argparse and optparse.
请参见针对Spyder的错误(Ipython IDE),其中-f
的处理程序而崩溃.
See this bug for Spyder (Ipython IDE), where -f
was being added as a command option and crashing as there was no handler for -f
.
您可以尝试检查当前正在播放的参数(就像对Spyder错误所做的一样),并放置一个虚拟处理程序.
You could try checking the arguments currently in play (as they did for the Spyder bug) and putting a dummy handler in place.
运行
import sys
print(sys.argv)
在Ipython内部,查看其输出.
inside Ipython and see what it outputs.
在我的系统上,它显示
['/usr/lib/python3.6/site-packages/ipykernel_launcher.py','-f','/run/user/1000/jupyter/kernel-7537e4dd-b5e2-407c-9d4c-7023575cfc7c. json']
['/usr/lib/python3.6/site-packages/ipykernel_launcher.py', '-f', '/run/user/1000/jupyter/kernel-7537e4dd-b5e2-407c-9d4c-7023575cfc7c.json']
Argparse假定第一个条目是程序名称(sys.argv[0]
).为了解决这个问题,我不得不打电话
Argparse assumes the first entry is the program name (sys.argv[0]
). In order to fix this, I had to call
parser = argparse.ArgumentParser(prog='myprogram', description='Foo')
...,现在argparse
可以在我的笔记本中使用.
... and now argparse
works in my notebook.
这篇关于Jupyter Notebook中的Argparse引发TypeError的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!