-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.py
More file actions
98 lines (79 loc) · 3.24 KB
/
Copy pathclient.py
File metadata and controls
98 lines (79 loc) · 3.24 KB
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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# windows: 记事本页面设置:页眉&l&f&r&d&t 页脚Page &p
# python client.py <url> <username> <password>
import os
import time
import argparse
import requests
import subprocess, sys
from base64 import b64decode
parser = argparse.ArgumentParser()
parser.add_argument('server', type=str, help='服务端地址')
parser.add_argument('user', type=str, help='用户名')
parser.add_argument('passwd', type=str, help='密码')
parser.add_argument('--saveDir', type=str, help='保存文件的目录, 默认./PrintFiles', default='./PrintFiles')
parser.add_argument('--saveExt', type=str, help='保存文件的扩展名, 默认txt', default='.txt')
args = parser.parse_args()
SERVER_URL = args.server
USERNAME = args.user
PASSWORD = args.passwd
SAVE_DIR = os.path.abspath(args.saveDir)
SAVE_EXT = args.saveExt
# 获取文件的 URL
SERVER_GET_FILE_URL = f"{SERVER_URL}/api/print"
# 标记文件的 URL, 最后拼接 SERVER_GET_FILE_URL + nonce
SERVER_MARK_FILE_URL = f"{SERVER_URL}/api/print/"
if not os.path.isdir(SAVE_DIR):
os.makedirs(SAVE_DIR)
def wait(t) :
print(f'等待 {t}s')
time.sleep(t)
while True:
try:
print('\n>>> REQUEST TIME = ', time.ctime())
response = requests.get(SERVER_GET_FILE_URL, auth=(USERNAME, PASSWORD))
if response.status_code == 404:
print("---没有可打印的文件 (服务端返回404) ---")
wait(10)
continue
if response.status_code != 200:
print(f"Error: {response.status_code}")
wait(10)
if response.status_code == 200:
file_data = response.json()
nonce = file_data["id"]
info = b64decode(file_data["info"])
data = b64decode(file_data["data"])
info = info.decode().replace('\n', '')
info = info.replace('*', '')
filename = os.path.join(SAVE_DIR, nonce[:8] + '_' + info + SAVE_EXT)
with open(filename, "wb") as f:
f.write(data)
# 标记文件
response = requests.delete(SERVER_MARK_FILE_URL + nonce, auth=(USERNAME, PASSWORD))
if response.status_code == 200:
# 调用系统打印机打印
if (len(data) > 10 * 1024) :
print(f"文件过大,无法打印")
os.system("pause")
else :
print(f"打印文件 {filename}")
# 在此处添加调用系统打印机的代码
# windows
os.startfile(filename, "print")
print(f"请在打印结束后取走所有文件,再按任意键继续")
os.system("pause")
# linux
# opener = "open" if sys.platform == "darwin" else "xdg-open"
# print_cmd = ["lp", filename]
# subprocess.call(print_cmd)
# # subprocess.call([opener, "print"])
# #os.startfile(filename, "print")
else:
print(f"确认文件 {nonce} 失败!")
os.remove(filename)
wait(5)
except Exception as e:
print(f"Error: {e}")
wait(30)