long blogs

进一步有进一步惊喜


  • Home
  • Archive
  • Tags
  •  

© 2025 long

Theme Typography by Makito

Proudly published with Hexo

python aria2 rpc

Posted at 2020-05-12 python aria2c 

添加新的下载任务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
def addDownloadTask(url,dir,out):
postdata = {
"jsonrpc": "2.0",
"id": "QXJpYU5nXzE1NDgzODg5MzhfMC4xMTYyODI2OTExMzMxMzczOA=="
}
rpc_request = postdata
rpc_request["method"] = "aria2.addUri"
# rpc 的选项,去掉--就可以了
options = {
"dir":dir,
"out":out,
"allow-overwrite":"true"
}
rpc_request["params"] = [[url],options]
response = requests.post(url=rpc_url, json=rpc_request)
if response.status_code == 200:
result = response.json().get("result", [])
print("gid: {}".format(result))
return result
else:
log("无法调用aria2")

查询当前的状态

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
def download_status(gid):
postdata = {
"jsonrpc": "2.0",
"id": "QXJpYU5nXzE1NDgzODg5MzhfMC4xMTYyODI2OTExMzMxMzczOA=="
}
rpc_request = postdata
rpc_request["method"] = "aria2.tellStatus"
rpc_request["params"] = [gid]
response = requests.post(url=rpc_url,json=rpc_request)
if response.status_code == 200:
result = response.json().get("result","")
if result != "":
status = result.get("status")
if status != "":
return status
return None

下载

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
def download(url,dir,out):
log("开始下载:{}".format(url))
gid = addDownloadTask(url,dir,out)
status = download_status(gid)
error = False
while True and not error:
if status == "active":
time.sleep(3)
print("下载中.....\n")
status = download_status(gid)
if status == "complete":
break
elif status == "waiting":
log("下载队列已满")
time.sleep(4)
elif status == "paused":
log("暂停下载")
break
elif status == "error":
log("下载错误")
error = True
break
elif status == "removed":
log("已经从下载队列中移除")
break
if error:
log("下载:{}出错".format(url))
return -1
else:
log("下载{}成功".format(url))
return 0
日志函数
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
day = datetime.datetime.now().strftime('%Y%m%d')
log_file = day+"_log.txt"
def log(value,print_flag = True):
logfile = open(log_file, 'a', encoding='utf-8')
if logfile.writable():
now_data = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
log_message = "时间:{} : log : {}\n".format(now_data, value)
if print_flag:
print(log_message)
logfile.write(log_message)
try:
logfile.close()
except IOError:
print("写入日志错误")
else:
return

Share 

 Previous post: go笔记(一) Next post: 下载bing首页图片 

© 2025 long

Theme Typography by Makito

Proudly published with Hexo