2013-11-25 39 views
0

我有一個簡單的實用程序腳本,用於下載給定URL的文件。它基本上只是一個Linux二進制「aria2c」的包裝。引用的字符串作爲Python腳本的可選參數

這裏是名爲getFile腳本:

#!/usr/bin/python 

# 
# SCRIPT NAME: getFile 
# PURPOSE: Download a file using up to 20 concurrent connections. 
# 

import os 
import sys 
import re 
import subprocess 

try: 
    fileToGet = sys.argv[1] 

    if os.path.exists(fileToGet) and not os.path.exists(fileToGet+'.aria2'): 
     print 'Skipping already-retrieved file: ' + fileToGet 
    else: 
     print 'Downloading file: ' + fileToGet 
     subprocess.Popen(["aria2c-1.8.0", "-s", "20", str(fileToGet), "--check-certificate=false"]).wait() # SSL 

except IndexError: 
    print 'You must enter a URI.' 

因此,例如,該命令將下載文件:

我想要做的就是允許一個可選的第二個參數(後
$ getFile http://upload.wikimedia.org/wikipedia/commons/8/8e/Self-portrait_with_Felt_Hat_by_Vincent_van_Gogh.jpg 

該URI)是一個帶引號的字符串。該字符串將是下載文件的新文件名。所以,下載完成後,文件將根據第二個參數重命名。使用上面的例子,我希望能夠進入:

$ getFile http://upload.wikimedia.org/wikipedia/commons/8/8e/Self-portrait_with_Felt_Hat_by_Vincent_van_Gogh.jpg "van-Gogh-painting.jpg" 

但我不知道如何把一個帶引號的字符串作爲可選參數。我怎樣才能做到這一點?

回答

2

只需測試sys.argv的長度;如果是超過2你有一個額外的參數:

if len(sys.argv) > 2: 
    filename = sys.argv[2] 
+0

哦,所以如果你將一個帶引號的字符串傳遞給Python,它會自動將它作爲一個單一的參數? – synaptik

+0

正確;引用是一個shell特性,與Python無關,真的。 –

+0

啊,好的,謝謝。我想我沒有對這個問題進行盡職調查。我至少應該嘗試一下,看看論證是如何工作的,而不是假設它不會像你描述的那樣工作。 :)所以,請原諒我的懶惰 - 非常感謝! – synaptik

1

外殼將通過它的第二個參數(一般),如果你在它們之間提供空間。

例如,這裏是test.py

import sys 

for i in sys.argv: 
    print(i) 

這裏是結果:

$ python test.py url "folder_name" 
test.py 
url 
folder_name 

的報價並不在所有問題,因爲它的外殼,而不是Python的處理。要得到它,只需要sys.argv[2]

希望這會有所幫助!

+0

謝謝。這很清楚。 – synaptik

+0

非常歡迎! – aIKid

相關問題