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)