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)
Edit:
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.
example.py
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__
running it
$ python example.py -copyDir --dir C:\\Users\\heinst\\Documents\\heinsts music
{'copyDir': True, 'dir': 'C:\\Users\\heinst\\Documents\\heinsts music'}