Raghavan
Raghavan

Reputation: 35

To ignore space in python argparse

For below code,

import os
import shutil
import argparse

if __name__ == '__main__':
    ap = argparse.ArgumentParser(description="Test")
    ap.add_argument('-s', '--values', action="store", dest="values", nargs='+', type=str)
    args = vars(ap.parse_args())
    print args

Input to this code is

$python test.py -s 90030#95000#m#6099#bc 90031#95001#s#1#+100ABC 90032#95002#s#2#+200ABC 90033#95003#s#3#+300 ABC

Actual output is

{'values': ['90030#95000#m#6099#base_case', '90031#95001#s#1#+100ABC', '90032#95002#s#2#+200ABC', '90033#95003#s#3#+300', 'ABC']}

But, I need output as below by ignoring space in third argument.

{'values': ['90030#95000#m#6099#base_case', '90031#95001#s#1#+100ABC', '90032#95002#s#2#+200ABC', '90033#95003#s#3#+300 ABC']}

May I know how to pass the correct arguments

Upvotes: 1

Views: 1818

Answers (3)

Martijn Pieters
Martijn Pieters

Reputation: 1122082

This is not an argparse problem. This is a shell problem. Your shell parses out the arguments and passes those on as an array to Python.

Tell the shell to not parse the string by putting quotes around those parts that form one argument:

$ python test.py -s 90030#95000#m#6099#bc 90031#95001#s#1#+100ABC \
    90032#95002#s#2#+200ABC "90033#95003#s#3#+300 ABC"

Note the "90033#95003#s#3#+300 ABC" as the last argument.

You can also use a backslash to escape the space:

$ python test.py -s 90030#95000#m#6099#bc 90031#95001#s#1#+100ABC \
    90032#95002#s#2#+200ABC 90033#95003#s#3#+300\ ABC

Demo using csh and your sample code:

% python test.py -s a b c
{'values': ['a', 'b', 'c']}
% python test.py -s a "b c"
{'values': ['a', 'b c']}
% python test.py -s 90030#95000#m#6099#bc 90031#95001#s#1#+100ABC 90032#95002#s#2#+200ABC 90033#95003#s#3#+300\ ABC
{'values': ['90030#95000#m#6099#bc', '90031#95001#s#1#+100ABC', '90032#95002#s#2#+200ABC', '90033#95003#s#3#+300 ABC']}

Upvotes: 3

mhawke
mhawke

Reputation: 87084

Surround the argument in either single or double quotes:

$ python test.py -s 90030#95000#m#6099#bc 90031#95001#s#1#+100ABC 90032#95002#s#2#+200ABC '90033#95003#s#3#+300 ABC'

Upvotes: 1

jgritty
jgritty

Reputation: 11925

Just surround the argument with quotes

python test.py -s 90030#95000#m#6099#bc 90031#95001#s#1#+100ABC 90032#95002#s#2#+200ABC "90033#95003#s#3#+300 ABC"

Upvotes: 1

Related Questions