[英]Passing command line argument with whitespace in Python
我正在嘗試通過命令行參數傳遞空格,但是sys.argv[1].strip()
僅給我該參數的第一個單詞
import sys, os
docname = sys.argv[1].strip()
e.g. $ python myscript.py argument with whitespace
如果我嘗試調試-docname給我輸出作為argument
而不是argument with whitespace
的argument with whitespace
我試圖用.replace(" ","%20")
方法替換空格,但這無濟於事
這與Python無關,與Shell無關。 該外殼程序具有一個稱為單詞拆分的功能,該功能使命令調用中的每個單詞成為一個單獨的單詞或arg。 要將結果作為一個帶有空格的單詞傳遞給Python,您必須轉義空格或使用引號。
./myscript.py 'argument with whitespace'
./myscript.py argument\ with\ whitespace
換句話說,當您的論點進入Python時,單詞拆分已經完成,未轉義的空格已經消除,並且sys.argv
(基本上)是單詞列表。
您需要使用argv[1:]
而不是argv[1]
:
docname = sys.argv[1:]
要將其打印為字符串:
' '.join(sys.argv[1:]) # Output: argument with whitespace
sys.argv[0]
是腳本本身的名稱, sys.argv[1:]
是傳遞給腳本的所有參數的列表。
輸出:
>>> python myscript.py argument with whitespace
['argument', 'with', 'whitespace']
您可以在命令行中使用雙引號字符串文字。 喜歡
python myscript.py "argument with whitespace"
其他:
python myscript.py argument with whitespace
在這里您也可以使用反斜杠:
python myscript.py argument\ with\ whitespace\
嘗試使用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)
結果是:
$ ./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
$
注意,-h / --help是“免費的”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.