Reputation: 8786
I have a python 2.7 script reading in input arguments through sys.argv[1:]. In order for the input arguments not to be broken up, there has to be quotes around it (otherwise sys.argv will break up the input arguments anywhere there is a space). How do I make sure that there are quotes surrounding it?
Example:
python example.py -copyDir --dir:"C:\Users\heinst\Documents\heinsts music"
Is there a way to check that the --dir:
argument has quotes around it? otherwise the list sys.argv would break it up into two parts: C:\Users\heinst\Documents\heinsts
and music
Upvotes: 4
Views: 2398
Reputation: 10870
You can use the standard package argparse
, it will take care of parsing the string properly to include the spaces. It also lets you have many other features (like automatically prepare the command help, here's a tutorial):
(Originally taken from this question)
I've finally got what the OP meant! Luckily argv is an ordered list so it is possible to parse the dir
with spaces.
This is also possible with argparse (see updated example below, solution shamelessly stolen from this question)
The downside to passing unquoted data is that the operating system escapes special chars (like backslashes) before they are passed to the python interpreter. So your script users would have to pass dirs with double quotes (c:\\Users\\
) ...
Not sure which is better but, I'd go with documenting the instructions in the opts (super easy with argparse) and in your documentation.
import argparse
class JoinAction(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
setattr(namespace, self.dest, " ".join(values))
parser = argparse.ArgumentParser()
parser.add_argument("-copyDir", action="store_true")
parser.add_argument("-d", "--dir", nargs="+", action=JoinAction)
args = parser.parse_args()
print args.__dict__
$ python example.py -copyDir --dir C:\\Users\\heinst\\Documents\\heinsts music
{'copyDir': True, 'dir': 'C:\\Users\\heinst\\Documents\\heinsts music'}
Upvotes: 2
Reputation: 32199
You can simply do something like:
if your_input[0] == your_input[-1] == '"':
#do something
where your_input
is the string: "C:\Users\heinst\Documents\heinsts music"
Upvotes: 1