Python-允许Argparse接受参数中的选项
我一直在尝试将命令传递给ArgParse,但是传递pacman -r
总是忽略-r
。我正在使用.parse_known_args()
尝试解决此问题,但它仍然不起作用。我还在使用nargs ='*'以具有未知数的参数
这是我所需的输出的想法:
>>> parser.parse_args() # Input: cmdname pacman -R sudo
['pacman', '-R', 'sudo']
当前输出:
>>> parser.parse_known_args() # Input: cmdname pacman -R sudo
['pacman']
如何将选项(例如-r -s)作为参数传递?是否使用.parse_args()或.parse_known_args()
编辑:示例代码:
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('arguments', nargs='*', help='Arguments to run')
args, extra = parser.parse_known_args()
commands = ''.join(args.arguments)
print(args.arguments, extra)
os.system(commands)
if __name__ == '__main__': main()
I've been trying to pass a command to argparse, however passing something like pacman -R
always ignores -R
. I'm using .parse_known_args()
to try and solve this, but it still doesn't work. I'm also using nargs='*' to have an unknown amount of arguments
Here's an idea of my desired output:
>>> parser.parse_args() # Input: cmdname pacman -R sudo
['pacman', '-R', 'sudo']
Current output:
>>> parser.parse_known_args() # Input: cmdname pacman -R sudo
['pacman']
How would I pass options (e.g. -R -S) as an argument? It doesn't matter if you use .parse_args() or .parse_known_args()
Edit: Sample code:
import argparse
def main():
parser = argparse.ArgumentParser()
parser.add_argument('arguments', nargs='*', help='Arguments to run')
args, extra = parser.parse_known_args()
commands = ''.join(args.arguments)
print(args.arguments, extra)
os.system(commands)
if __name__ == '__main__': main()
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
argparse
将'-r'解释为标志,因此参数
只能将字符串获取到那一点。其余部分进入extras
。这在argparse
中深深根深蒂固:您可以使用' - '强制处理所有以下字符串作为参数
argparse
interprets '-R' as a flag, soarguments
only gets the strings up to that point. The rest goes intoextras
. That's deeply ingrained behavior inargparse
:You can use a '--' to force the handling of all following strings as arguments