From 7f892ee70e7193ce512cb89af70f7c44775ee318 Mon Sep 17 00:00:00 2001 From: Ching L Date: Wed, 15 Jan 2025 17:20:11 +0800 Subject: [PATCH] =?UTF-8?q?feat(print=5Fsth):=20=E5=A2=9E=E5=8A=A0?= =?UTF-8?q?=E6=89=93=E5=8D=B0=E8=84=9A=E6=9C=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- print_sth.py | 40 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 print_sth.py diff --git a/print_sth.py b/print_sth.py new file mode 100644 index 0000000..ebda558 --- /dev/null +++ b/print_sth.py @@ -0,0 +1,40 @@ +import subprocess +import os + +def list_printers(): + """ + 通过 lpstat -p 命令列出所有可用打印机 + """ + try: + output = subprocess.check_output(["lpstat", "-p"], text=True) + print("可用打印机列表:\n", output) + except FileNotFoundError: + print("系统未安装或未找到 'lpstat' 命令,请检查 CUPS 是否安装。") + except Exception as e: + print(f"查询打印机时出错:{e}") + +def print_file(printer_name, file_path): + """ + 使用指定的打印机打印文件 + """ + if not os.path.exists(file_path): + print("错误:文件 %s 不存在。" % file_path) + return + + try: + subprocess.run(["lp", "-d", printer_name, file_path], check=True) + print(f"文件已发送到打印机:{printer_name}") + except FileNotFoundError: + print("系统未安装或未找到 'lp' 命令,请检查 CUPS 是否安装。") + except subprocess.CalledProcessError as e: + print(f"打印失败:{e}") + +if __name__ == "__main__": + list_printers() + chosen_printer = input("请输入要使用的打印机名称:").strip() + file_to_print = input("请输入要打印的文件路径:").strip() + file_to_print = file_to_print.replace("\ ", " ") + print(f"打印机:{chosen_printer},文件:{file_to_print}") + file_to_print = os.path.normpath(file_to_print) + + print_file(chosen_printer, file_to_print)