简体   繁体   中英

Passing command line argument with whitespace in Python

I am trying to pass the command line argument with white space in it, but sys.argv[1].strip() gives me only first word of the argument

import sys, os
docname = sys.argv[1].strip()

 e.g. $ python myscript.py argument with whitespace

If I try to debug - docname gives me output as argument instead of argument with whitespace

I tried to replace the white space with .replace(" ","%20") method but that didn't help

This has nothing to do with Python and everything to do with the shell. The shell has a feature called wordsplitting that makes each word in your command invocation a separate word, or arg. To pass the result to Python as a single word with spaces in it, you must either escape the spaces, or use quotes.

./myscript.py 'argument with whitespace'
./myscript.py argument\ with\ whitespace

In other words, by the time your arguments get to Python, wordsplitting has already been done, the unescaped whitespace has been eliminated and sys.argv is (basically) a list of words.

You need to use argv[1:] instead of argv[1] :

docname = sys.argv[1:]

To print it as a string:

' '.join(sys.argv[1:])  # Output: argument with whitespace

sys.argv[0] is the name of the script itself, and sys.argv[1:] is a list of all arguments passed to your script.

Output:

>>> python myscript.py argument with whitespace
['argument', 'with', 'whitespace']

Using strings in command line

You can use double quoted string literal in the command line. Like

python myscript.py "argument with whitespace"

Else of:

python myscript.py argument with whitespace

Using backslashes

Here you can use backslashes too:

python myscript.py argument\ with\ whitespace\

Try it with argparse:

#!/usr/bin/env python3

import argparse

parser = argparse.ArgumentParser()
parser.add_argument("-f", "--file",
                    help="specify the file to be used (enclose in double-quotes if necessary)",
                    type=str)
args = parser.parse_args()

if args.file:
    print("The file requested is:", args.file)

The results are:

$ ./ex_filename.py --help
usage: ex_filename.py [-h] [-f FILE]

optional arguments:
  -h, --help            show this help message and exit
  -f FILE, --file FILE  specify the file to be used (enclose in double-quotes
                        if necessary)

$ ./ex_filename.py -f "~/testfiles/file with whitespace.txt"
The file requested is: ~/testfiles/file with whitespace.txt
$ 

Note that the -h / --help comes "free".

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