简体   繁体   中英

Passing an argument with whitespace characters into argparse

My Python script:

import os
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-l', '--l', nargs='+', help='list = [title, HTML]')
args = parser.parse_args()
print args.l

When I execute the script inside Keyboard Maestro, I do it like this:

python  ~/Desktop/save_html.py -l $KMVAR_javascriptTITLE

It's working, but argparse is parsing anything with a space.

First Name turns into ['First', 'Last'] . If I understand it correctly, arparse is reading my command like:

python ~/Desktop/save_html.py -l First Last

when what I really want is:

python ~/Desktop/save_html.py -l "First Last"

How do I pass a variable into argparse and it reads it as 1 string?

Changing my comment to an answer

How about if you do python ~/Desktop/save_html.py -l "$KMVAR_javascriptTITLE" ? escape the quotes if necessary

You could use a CustomAction to do this:

import os
import argparse


class CustomAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, " ".join(values))


parser = argparse.ArgumentParser()
parser.add_argument('-l', '--l', action=CustomAction, type=str, nargs='+', help='list = [title, HTML]')
args = parser.parse_args()
print args.l

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM