Handle spaces in argparse input

后端 未结 5 1979
逝去的感伤
逝去的感伤 2020-12-28 12:52

Using python and argparse, the user could input a file name with -d as the flag.

parser.add_argument(\"-d\", \"--dmp\", default=None)

Howev

相关标签:
5条回答
  • 2020-12-28 13:18

    Simple solution: argparse considers a space filled string as a single argument if it is encapsulated by quotation marks.

    This input worked and "solved" the problem:

    -d "C:\SMTHNG\Name with spaces\MORE\file.csv"
    

    NOTICE: argument has "" around it.

    0 讨论(0)
  • 2020-12-28 13:22

    After some experiments (python 2.7 Win10) I found out that the golden rule is to put quotes ("") around arguments which contain spaces and do NOT put if there are no spaces in argument. Even if you are passing a string/path. Also putting a single quotes ('') is a bad idea, at least for Windows.

    Small example: python script.py --path ....\Some_Folder\ --string "Here goes a string"

    0 讨论(0)
  • 2020-12-28 13:32

    For those who can't parse arguments and still get "error: unrecognized arguments:" I found a workaround:

    parser.add_argument('-d', '--dmp', nargs='+', ...)
    opts = parser.parse_args()
    

    and then when you want to use it just do

    ' '.join(opts.dmp)
    
    0 讨论(0)
  • 2020-12-28 13:37

    Bumped into this problem today too.

    -d "foo bar"
    

    didn't help. I had to add the equal sign

    -d="foo bar"
    

    and then it did work.

    0 讨论(0)
  • 2020-12-28 13:39

    You need to surround your path with quotes such as:

    python programname.py -path "c:\My path with spaces"
    

    In the argument parse you get a list with one element. You then have to read it like:

    path = args.path[0]
    
    0 讨论(0)
提交回复
热议问题