Passing command line argument with whitespace in Python
Solution 1
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.
Solution 2
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']
Solution 3
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\
Darshan Deshmukh
DevOps Engineer Automation geek Firm beliver in context driven testing and exploratory testing
Updated on June 09, 2022Comments
-
Darshan Deshmukh almost 2 years
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 argumentimport 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 ofargument with whitespace
I tried to replace the white space with
.replace(" ","%20")
method but that didn't help -
mbednarski over 7 yearsEscaping would be:
./myscript.py argument\ with\ whitespace
-
ettanany over 7 yearsI know that
strip()
is astr
method, that's why I am usingsys.argv[1:]
-
Organis over 7 yearssys.argv is a list thus sys.argv[1:] is a slice of that list.
-
Organis over 7 yearsIt is not me who did it.
-
ettanany over 7 years@Organis I do not mean you!
sys.argv[0]
is the name of the script itself, that's why we usesys.argv[1:]
to read the rest of options -
DeanM over 5 yearsNote that you need to use double-quotes here. Single-quotes won't work.