Frage

I have simple utility script that I use to download files given a URL. It's basically just a wrapper around the Linux binary "aria2c".

Here is the script named 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.'

So, for example, this command would download a file:

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

What I want to do is permit an optional second argument (after the URI) that is a quoted string. This string will be the new filename of the downloaded file. So, after the download finishes, the file is renamed according to the second argument. Using the example above, I would like to be able to enter:

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

But I don't know how to take a quoted string as an optional argument. How can I do this?

War es hilfreich?

Lösung

Just test the length of sys.argv; if it is more than 2 you have an extra argument:

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

Andere Tipps

The shell will pass it as a second argument (normally) if you provide spaces between them.

For example, here is test.py:

import sys

for i in sys.argv:
    print(i)

And here is the result:

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

The quotes doesn't matter at all, as it's handled in the shell, not python. To get it, just take sys.argv[2].

Hope this helps!

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top