Python-Ref > User interaction > User input > Passing arguments containing whitespace
 
 

<-^^->
Klíčová slova
Moduly
Knihovní funkce

Passing arguments containing whitespace

When using the command line arguments, one has to bear in mind a few features of this approach.
The first one is that the command line arguments are passed as a list obtained by splitting the command-line using the whitespace as a separating character. Therefor one has to take care when passing values, often filenames, containing whitespace characters.
Expand/Shrink
Argumenty příkazové řádky:
python userinp2.1.py filename with spaces.txt
Zdroj: (userinp2.1.py)
  1   import sys
  2   
  3   print sys.argv
  4   print sys.argv[0]
  5   print sys.argv[1:]
stdout:
['userinp2.1.py', 'filename', 'with', 'spaces.txt']
userinp2.1.py
['filename', 'with', 'spaces.txt']
Doba běhu: 21.1 ms
The above example shows that such value will be split to several different input values.
The solution to this problem is to use quotes..
Expand/Shrink
Argumenty příkazové řádky:
python userinp2.1.py "filename with spaces.txt"
Zdroj: (userinp2.1.py)
  1   import sys
  2   
  3   print sys.argv
  4   print sys.argv[0]
  5   print sys.argv[1:]
stdout:
['userinp2.1.py', 'filename with spaces.txt']
userinp2.1.py
['filename with spaces.txt']
Doba běhu: 21.5 ms
.. or escaping of the whitespace characters.
Expand/Shrink
Argumenty příkazové řádky:
python userinp2.1.py filename\ with\ spaces.txt
Zdroj: (userinp2.1.py)
  1   import sys
  2   
  3   print sys.argv
  4   print sys.argv[0]
  5   print sys.argv[1:]
stdout:
['userinp2.1.py', 'filename with spaces.txt']
userinp2.1.py
['filename with spaces.txt']
Doba běhu: 20.9 ms