How can I use python's argparse with a predefined argument string?

試著忘記壹切 提交于 2019-12-17 18:37:36

问题


I want to use the pythons argparse module to parse my cli parameter string. This works for the parameters a pass from terminal, but not with a given string.

import argparse

parser = argparse.ArgumentParser(description='Argparse Test script')
parser.add_argument("param", help='some parameter')

argString = 'someTestFile'
print(argString)

args = parser.parse_args(argString)

If I run this script I get this output:

~/someTestFile
usage: argparsetest.py [-h] param
argparsetest.py: error: unrecognized arguments: o m e T e s t F i l e

The ~/someTestFile is somehow transformed in o m e T e s t F i l e. As already mentioned, it works if I pass the filename from the terminal.

I could imagine, that this has something to do with string encodings. Does someone has an idea how to fix this?


回答1:


Ah, no no no. parser.parse_args() expects a sequence in the same form as sys.argv[1:]. If you treat a string like a sys.argv sequence, you get ['s', 'o', 'm', 'e', 'T', 'e', 's', 't', 'F', 'i', 'l', 'e']. 's' becomes the relevant argument, and then the rest of the string is unparseable.

Instead, you probably want to pass in parser.parse_args(['someTestFile'])




回答2:


Another option is to use shlex.split. It it especially very convenient if you have real CLI arguments string:

import shlex
argString = '-vvvv -c "yes" --foo bar --some_flag'
args = parser.parse_args(shlex.split(argString))



回答3:


Just like the default sys.argv is a list, your arguments have to be a list as well.

args = parser.parse_args([argString])



回答4:


Simply split your command string :

args = parser.parse_args(argString.split())

A complete example to showcase :

import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('--dummy_opt', nargs='*', type=int, help='some ids')
    argString = "--dummy_opt 128 128"
    args = parser.parse_args(argString.split())

    print(args)

will output :

Namespace(pic_resize=[128, 128])



来源:https://stackoverflow.com/questions/8878478/how-can-i-use-pythons-argparse-with-a-predefined-argument-string

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!