Python:如何处理argparse的异常?
我想这样使用我的程序:
pythonScript -f filename
但如果我忘记了 -f,我仍然想获取文件名。
所以我希望这个“pythonScript filename”也能工作(->我可以从 args.fileName 或处理异常中获取文件名)
我知道这一定很容易,我只是找不到方法来做到这一点。有人可以帮我吗?谢谢
import argparse
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', action='store', dest='fileName',
default = None, type=str, help='The file name')
try:
args = parser.parse_args()
except:
print "xxx"
I'd like to use my program this way:
pythonScript -f filename
But if I forgot -f, I still want to get the filename.
So I want this "pythonScript filename" also work (->I can get the file name from args.fileName or from handling the exception)
I know this must be easy, I just can not find a way to do it. Anyone can help me out? Thanks
import argparse
parser = argparse.ArgumentParser(prog='PROG')
parser.add_argument('-f', action='store', dest='fileName',
default = None, type=str, help='The file name')
try:
args = parser.parse_args()
except:
print "xxx"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您希望 -f 是必需的,您可以使用 argparse。只需在 add_argument 函数中包含“required = True”即可。
请记住,必需选项是矛盾的。不建议将选项设为必需,但有时会有帮助。如果未给出该选项,则目标仍为“无”值(或者它会被分配给您指定的任何默认值,在示例中为“无”)。
编辑:刚刚看到您的编辑,我明白您现在在问什么。在我看来,optparse 使这个变得更简单。似乎对于带有 argparse 的位置参数,您需要使用 add_argument。
让 argparse 为你做这件事确实没有简单的方法。您可以通过以下方式创造性地模拟它:
基本上,如果给出了文件选项,它会覆盖位置参数。
If you want -f to be required, you can make it that way with argparse. Just include "required = True" inside of the add_argument function.
Remember that required option is contradictory. It's not suggested to make options required, but sometimes helpful. If the option is not given, then the destination remains the None value (or it gets assigned whatever default value you've given, which is None in your example).
EDIT: Just saw your edit and I understand what you're asking now. optparse makes this simpler IMO. It seems for positional arguments with argparse, you need to use add_argument.
There's really no easy way to have argparse do it for you. You can simulate it a little bit creatively with the following:
Basically, if there's a file option given, it overwrites the positional argument.