---
title: "样例代码学习"
author: "androider"
date: "2009-07-05T07:08:39Z"
tags: []
slug: "untitled"
draft: false
lastmod: "2009-07-05T11:24:57Z"
id: 420329
url: "https://androider.iteye.com/blog/420329"
---

```
#!/usr/bin/env python
#pyaria2.py

import os, sys, urllib

def usage():
    print """Usage: python tharia2.py [OPTIONS] URL

OPTIONS: As same as options of aria2c"""

def get_url_list(url, listpath):
    if not os.path.exists(listpath):
        print "Getting URL list, please wait..."
        f = urllib.urlopen("http://cocobear.info/demo/pythunder/?url=%s" % url)
        lst = open(listpath, "w+")
        lst.writelines(f.readlines())
        f.close
        lst.seek(0)
    else:
        print "Found existing url list: ", listpath
        lst = open(listpath)

    url_list = [line[:-1] for line in lst]
    lst.close()
    print "Recieved %d url(s)." % len(url_list)
    return " ".join(url_list)

def download(url):
    for prefix in (r"http://", r"https://", r"ftp://"):
        if url.startswith(prefix):
            break
    else:
        print "Invalid URL: %s" % url
        exit()

    listdir = os.path.expanduser("~/.tharia2/list/")
    listfile = os.path.split(url)[-1] + ".list"
    if not os.path.exists(listdir):
        os.makedirs(listdir)
    listpath = os.path.join(listdir, listfile)

    url_list = get_url_list(url, listpath)
    cmd = " ".join(("aria2c -c", " ".join(sys.argv[1:-1]), url_list))
    print "Executing command: %s" % cmd
    if not os.system(cmd):
        os.remove(listpath)

if __name__ == "__main__":
    if len(sys.argv) > 1:
        download(sys.argv[-1])
    else:
        usage()
```

 

1，sys.argv\[-1]表示获取Lists的最后一个元素，如 names=\["1", "2", "3", "4"]

     则names\[-1]为4，names\[:-1]为1，2，3表示从开始到该元素，names\[-3, -1]为2，3等

2，sys.argv

3，os

4，file

5，urllib

 

 [http://www.kissuki.com/2009/05/python-版-linux-下的迅雷/](http://www.kissuki.com/2009/05/python-%E7%89%88-linux-%E4%B8%8B%E7%9A%84%E8%BF%85%E9%9B%B7/)