### conn.setDefault(name) / conn.getDefault() Source: https://context7.com/openprinting/pycups/llms.txt Gets or sets the system's default printer. ```APIDOC ## conn.setDefault(name) / conn.getDefault() ### Description Gets or sets the system default printer. ### Parameters * **name** (str) - Optional. The name of the printer to set as default. If not provided, returns the current default. ### Returns * **str** - The name of the default printer. ``` -------------------------------- ### List All Destinations (including instances) Source: https://context7.com/openprinting/pycups/llms.txt Get a dictionary of all destinations, keyed by `(name, instance)` tuples, using `conn.getDests()`. The system default is identified by `(None, None)`. ```python import cups conn = cups.Connection() dests = conn.getDests() default_dest = dests.get((None, None)) if default_dest: print("Default printer:", default_dest.name) for (name, instance), dest in dests.items(): if name is None: continue label = f"{name}/{instance}" if instance else name marker = " (default)" if dest.is_default else "" print(f" {label}{marker}") print(f" options: {dest.options}") ``` -------------------------------- ### Serialize PPD to File Descriptor and String Source: https://context7.com/openprinting/pycups/llms.txt This example shows how to write a modified PPD file (after marking options) to a file descriptor and also emit a specific section (JCL header) as a string. Requires a PPD file for 'LaserJet'. ```python import cups, os, tempfile conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) ppd.markOption("PageSize", "A4") # Write modified PPD to a temp file fd, out_path = tempfile.mkstemp(suffix=".ppd") ppd.writeFd(fd) os.close(fd) print(f"Modified PPD written to {out_path}") # Or emit a section as a string header_str = ppd.emitString(cups.PPD_ORDER_JCL, 0) print(header_str[:200]) ``` -------------------------------- ### Set Banner Pages (Python) Source: https://context7.com/openprinting/pycups/llms.txt Configures the start and end banner page types for a printer queue. Can be set to 'standard' or 'none' to disable banners. ```python import cups conn = cups.Connection() conn.setPrinterJobSheets("LaserJet", "standard", "standard") conn.setPrinterJobSheets("LaserJet", "none", "none") # disable banners ``` -------------------------------- ### cups.require(version) Source: https://context7.com/openprinting/pycups/llms.txt Asserts that the installed pycups version meets a specified minimum version. Raises `RuntimeError` if the version is insufficient. ```APIDOC ## cups.require(version) ### Description Raises `RuntimeError` if the installed pycups is older than the specified version string. ### Parameters - **version** (str) - The minimum required version string (e.g., "2.0.0"). ### Raises - **RuntimeError** - If the installed pycups version is older than the specified version. ### Example ```python import cups try: cups.require("2.0.0") except RuntimeError as e: raise SystemExit(f"pycups too old: {e}") ``` ``` -------------------------------- ### conn.setPrinterJobSheets(name, start, end) Source: https://context7.com/openprinting/pycups/llms.txt Configures the banner pages (start and end sheets) for jobs printed on a specific queue. ```APIDOC ## conn.setPrinterJobSheets(name, start, end) ### Description Sets the banner pages for a printer queue. ### Parameters * **name** (str) - The name of the printer. * **start** (str) - The type of start banner page ('standard', 'none'). * **end** (str) - The type of end banner page ('standard', 'none'). ``` -------------------------------- ### Handle CUPS IPPError Exception Source: https://context7.com/openprinting/pycups/llms.txt This example shows how to catch and handle `cups.IPPError`, extracting the status code and description string. It attempts to cancel a non-existent job to trigger the error. ```python import cups conn = cups.Connection() # IPPError: (status_code, description_string) try: conn.cancelJob(99999) except cups.IPPError as e: status, desc = e.args print(f"IPP error {status} ({cups.ippErrorString(status)}): {desc}") # IPP error 1029 (client-error-not-found): Not Found ``` -------------------------------- ### Set and Get Default CUPS Server Source: https://context7.com/openprinting/pycups/llms.txt Establishes or retrieves the default hostname for new `Connection` objects. Any subsequent `cups.Connection()` calls without explicit host arguments will use this server. ```python import cups cups.setServer("cups.internal.example.com") print(cups.getServer()) # "cups.internal.example.com" conn = cups.Connection() # connects to cups.internal.example.com ``` -------------------------------- ### Assert Minimum pycups Version Source: https://context7.com/openprinting/pycups/llms.txt Ensure the installed pycups version meets a minimum requirement using `cups.require`. Raises `RuntimeError` if the version is too old. ```python import cups try: cups.require("2.0.0") except RuntimeError as e: raise SystemExit(f"pycups too old: {e}") ``` -------------------------------- ### Set and Get Encryption Policy Source: https://context7.com/openprinting/pycups/llms.txt Controls the TLS negotiation policy for all future connections. Use constants like `cups.HTTP_ENCRYPT_ALWAYS`, `cups.HTTP_ENCRYPT_IF_REQUESTED`, `cups.HTTP_ENCRYPT_NEVER`, or `cups.HTTP_ENCRYPT_REQUIRED`. ```python import cups cups.setEncryption(cups.HTTP_ENCRYPT_REQUIRED) print(cups.getEncryption()) # integer value of HTTP_ENCRYPT_REQUIRED ``` -------------------------------- ### Check PPD Conflicts and Iterate Options Source: https://context7.com/openprinting/pycups/llms.txt This snippet demonstrates how to check for constraint violations within a PPD file and iterate through its option groups and options. No specific setup is required beyond having a PPD object. ```python import cups conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) # Check for constraint violations conflict_count = ppd.conflicts() print(f"Conflicts: {conflict_count}") # Iterate option groups and options for group in ppd.optionGroups: print(f"Group: {group.name} ({group.text})") for opt in group.options: print(f" Option: {opt.keyword} default={opt.defchoice}") for choice in opt.choices: print(f" [{choice['choice']}] {choice['text']}") ``` -------------------------------- ### Get or Set Default Printer (Python) Source: https://context7.com/openprinting/pycups/llms.txt Retrieves the current system default printer or sets a new default printer. Use to manage the user's preferred printing destination. ```python import cups conn = cups.Connection() print("Current default:", conn.getDefault()) conn.setDefault("HP_Color") print("New default:", conn.getDefault()) ``` -------------------------------- ### Set and Get CUPS Username Source: https://context7.com/openprinting/pycups/llms.txt Configures the username for subsequent IPP requests. This must be called before creating a `Connection` object to ensure it takes effect. ```python import cups cups.setUser("jdoe") print(cups.getUser()) # "jdoe" ``` -------------------------------- ### Fetch Detailed Printer Attributes Source: https://context7.com/openprinting/pycups/llms.txt Get detailed IPP attributes for a single printer using `conn.getPrinterAttributes()`. Specify either `name` or `uri`, and a list of requested attributes. ```python import cups conn = cups.Connection() attrs = conn.getPrinterAttributes( name="LaserJet", requested_attributes=["printer-state", "printer-state-reasons", "job-sheets-supported", "media-supported"] ) print("State:", attrs.get("printer-state")) print("Job sheets supported:", attrs.get("job-sheets-supported")) print("Media:", attrs.get("media-supported")) ``` -------------------------------- ### conn.getDevices(limit, exclude_schemes, include_schemes, timeout) Source: https://context7.com/openprinting/pycups/llms.txt Discovers devices connected to the system. Returns a dictionary keyed by device URI, with each value containing device details. ```APIDOC ## conn.getDevices(limit, exclude_schemes, include_schemes, timeout) ### Description Discovers devices. Returns a dict keyed by device URI; each value contains `device-class`, `device-make-and-model`, `device-info`, etc. ### Parameters * **limit** (int) - Optional. The maximum number of devices to return. * **exclude_schemes** (list) - Optional. A list of device schemes to exclude. * **include_schemes** (list) - Optional. A list of device schemes to include. * **timeout** (int) - Optional. The timeout in seconds for device discovery. ### Returns * **dict** - A dictionary where keys are device URIs and values are dictionaries of device information. ``` -------------------------------- ### Discover Devices (Python) Source: https://context7.com/openprinting/pycups/llms.txt Discovers available printing devices and returns them as a dictionary keyed by device URI. Excludes devices found via 'dnssd' and has a timeout. Useful for finding network or local printers. ```python import cups conn = cups.Connection() devices = conn.getDevices(timeout=10, exclude_schemes=["dnssd"]) for uri, info in devices.items(): print(f" {uri}: {info.get('device-make-and-model')}") ``` -------------------------------- ### Get IPP Status Code String Source: https://context7.com/openprinting/pycups/llms.txt Convert an IPP status code to a human-readable string using `cups.ippErrorString`. This helps in debugging IPP communication. ```python import cups print(cups.ippErrorString(cups.IPP_STATUS_ERROR_NOT_FOUND)) # "client-error-not-found" ``` -------------------------------- ### getServerPPD Source: https://context7.com/openprinting/pycups/llms.txt Fetches a named PPD (PostScript Printer Description) file from the CUPS server. ```APIDOC ## getServerPPD(ppd_name) ### Description Fetches a named PPD (PostScript Printer Description) file from the CUPS server. ### Method `conn.getServerPPD(ppd_name)` ### Parameters - **ppd_name** (str) - The name of the PPD file to fetch. ### Request Example ```python import cups conn = cups.Connection() ppds = conn.getPPDs(ppd_make="HP", limit=1) ppd_name = next(iter(ppds)) path = conn.getServerPPD(ppd_name) ppd_obj = cups.PPD(path) ``` ### Response #### Success Response (str) - Returns the path to the fetched PPD file on the server. ``` -------------------------------- ### Fetch PPD with Cache Check (Python) Source: https://context7.com/openprinting/pycups/llms.txt Fetches a printer's PPD file, checking the cache first. Returns HTTP status, modification time, and filename. Use when the PPD might already be cached. ```python import cups conn = cups.Connection() status, modtime, fname = conn.getPPD3("LaserJet") if status == cups.HTTP_STATUS_OK: ppd = cups.PPD(fname) elif status == cups.HTTP_STATUS_NOT_MODIFIED: print("Cached PPD still current") ``` -------------------------------- ### Set and Get Default IPP Port Source: https://context7.com/openprinting/pycups/llms.txt Configures or retrieves the default IPP port number for new `Connection` objects. The standard port is 631. ```python import cups cups.setPort(631) print(cups.getPort()) # 631 ``` -------------------------------- ### List Available PPDs (Python) Source: https://context7.com/openprinting/pycups/llms.txt Retrieves a dictionary of all available PPDs, keyed by PPD name. Supports filtering by attributes like 'ppd-make'. Use to discover available printer drivers. ```python import cups conn = cups.Connection() # All PPDs all_ppds = conn.getPPDs() print(f"Total PPDs: {len(all_ppds)}") # Filter by manufacturer hp_ppds = conn.getPPDs(ppd_make="HP") for ppd_name, attrs in list(hp_ppds.items())[:5]: print(f" {ppd_name}: {attrs.get('ppd-make-and-model')}") # Using getPPDs2 for list-valued attributes hp_ppds2 = conn.getPPDs2(ppd_make="HP", limit=10) ``` -------------------------------- ### Export Printer to Samba Source: https://context7.com/openprinting/pycups/llms.txt Exports a CUPS printer to a Samba share. Requires root privileges. ```python import cups conn = cups.Connection() cups.setUser("root") conn.adminExportSamba("LaserJet", "\\fileserver", "Administrator", "adminpass") ``` -------------------------------- ### Connection.getDests() Source: https://context7.com/openprinting/pycups/llms.txt Returns a dictionary of all destinations, including instances. The system default destination is identified by the key `(None, None)`. ```APIDOC ## conn.getDests() ### Description Returns a dict keyed by `(name, instance)` tuples; the entry `(None, None)` identifies the system default. ### Returns - **dict** - A dictionary where keys are `(name, instance)` tuples and values are `Destination` objects. ### Example ```python import cups conn = cups.Connection() dests = conn.getDests() default_dest = dests.get((None, None)) if default_dest: print("Default printer:", default_dest.name) for (name, instance), dest in dests.items(): if name is None: continue label = f"{name}/{instance}" if instance else name marker = " (default)" if dest.is_default else "" print(f" {label}{marker}") print(f" options: {dest.options}") ``` ``` -------------------------------- ### Create CUPS Event Subscription Source: https://context7.com/openprinting/pycups/llms.txt Creates a new event subscription for specified events on a CUPS URI with a given lease duration. ```python import cups conn = cups.Connection() sub_id = conn.createSubscription( "ipp://localhost/", events=["printer-state-changed", "job-state-changed", "printer-added", "printer-deleted"], lease_duration=3600 ) print(f"Subscription ID: {sub_id}") ``` -------------------------------- ### Get IPP Operation Code String Source: https://context7.com/openprinting/pycups/llms.txt Convert an IPP operation code to its string representation using `cups.ippOpString`. Useful for logging and understanding IPP requests. ```python import cups print(cups.ippOpString(cups.IPP_OP_PRINT_JOB)) # "Print-Job" ``` -------------------------------- ### Find PPD Option by Keyword and Display Details Source: https://context7.com/openprinting/pycups/llms.txt This snippet shows how to find a specific option in a PPD file using its keyword ('PageSize') and then prints its UI type, choices, and default selection. Requires a PPD file for 'LaserJet'. ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) opt = ppd.findOption("PageSize") if opt: print(f"PageSize UI: {opt.ui}") print(f"Choices: {[c['choice'] for c in opt.choices]}") print(f"Default: {opt.defchoice}") ``` -------------------------------- ### adminExportSamba Source: https://context7.com/openprinting/pycups/llms.txt Exports a printer configuration to a Samba share. ```APIDOC ## adminExportSamba(name, samba_server, samba_username, samba_password) ### Description Exports a printer configuration to a Samba share. ### Method `conn.adminExportSamba(name, samba_server, samba_username, samba_password)` ### Parameters - **name** (str) - The name of the printer to export. - **samba_server** (str) - The network path to the Samba server (e.g., '\\fileserver'). - **samba_username** (str) - The username for accessing the Samba share. - **samba_password** (str) - The password for accessing the Samba share. ### Request Example ```python import cups conn = cups.Connection() cups.setUser("root") conn.adminExportSamba("LaserJet", "\\\fileserver", "Administrator", "adminpass") ``` ``` -------------------------------- ### cups.Connection Source: https://context7.com/openprinting/pycups/llms.txt Constructor for the primary object; connects via HTTP to the CUPS daemon. Raises RuntimeError if the connection cannot be established. ```APIDOC ## cups.Connection(host, port, encryption) ### Description Constructor for the primary object; connects via HTTP to the CUPS daemon. `host`, `port`, and `encryption` are optional and default to the values returned by `cups.getServer()`, `cups.getPort()`, and `cups.getEncryption()`. Raises `RuntimeError` if the connection cannot be established. ### Method Constructor ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import cups # Set connection defaults before constructing (optional) cups.setServer("localhost") cups.setUser("admin") cups.setEncryption(cups.HTTP_ENCRYPT_IF_REQUESTED) # Simple password callback def pw_callback(prompt, conn, method, resource, context): return "secret" # return None to abort cups.setPasswordCB2(pw_callback) try: conn = cups.Connection() print(repr(conn)) # except RuntimeError as e: print("Cannot connect:", e) # Connect to a remote server explicitly remote = cups.Connection(host="printserver.example.com", port=631, encryption=cups.HTTP_ENCRYPT_ALWAYS) ``` ### Response #### Success Response (200) Represents an authenticated HTTP/IPP connection to a CUPS server. #### Response Example ``` ``` ``` -------------------------------- ### Search PPD Attributes by Name and Spec Source: https://context7.com/openprinting/pycups/llms.txt This code demonstrates searching for PPD attributes like 'DefaultColorSpace' and iterating through all '*cupsFilter' attributes. It requires a PPD file for 'LaserJet'. ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) attr = ppd.findAttr("DefaultColorSpace", "") if attr: print(f"DefaultColorSpace: {attr.value}") # Iterate all *cupsFilter attributes attr = ppd.findAttr("cupsFilter", None) while attr: print(f"cupsFilter: {attr.value}") attr = ppd.findNextAttr("cupsFilter", None) ``` -------------------------------- ### getFile / putFile Source: https://context7.com/openprinting/pycups/llms.txt Transfers CUPS server files, allowing for downloading and uploading of configuration and log files. ```APIDOC ## getFile(resource, filename, fd=None, file=None) / putFile(resource, filename, fd=None, file=None) ### Description Fetches or uploads CUPS server configuration and log files. ### Method `conn.getFile(resource, filename, fd, file)` `conn.putFile(resource, filename, fd, file)` ### Parameters - **resource** (str) - The path to the resource on the CUPS server. - **filename** (str) - The local path to save or read the file from. - **fd** (int, optional) - File descriptor for the file. - **file** (file object, optional) - File object for the file. ### Request Example ```python import cups conn = cups.Connection() cups.setUser("root") # Download cupsd.conf conn.getFile("/admin/conf/cupsd.conf", filename="/tmp/cupsd.conf.bak") # Modify and re-upload with open("/tmp/cupsd.conf.bak") as f: data = f.read().replace("LogLevel warn", "LogLevel debug") with open("/tmp/cupsd.conf.new", "w") as f: f.write(data) conn.putFile("/admin/conf/cupsd.conf", filename="/tmp/cupsd.conf.new") ``` ``` -------------------------------- ### conn.printFiles Source: https://context7.com/openprinting/pycups/llms.txt Submits multiple files as a single print job. ```APIDOC ## conn.printFiles(printer, filenames, title, options) ### Description Submit multiple files as one job. ### Parameters #### Path Parameters - **printer** (str) - Required - The name of the printer. - **filenames** (list[str]) - Required - A list of paths to the files to print. - **title** (str) - Required - The title of the print job. #### Query Parameters - **options** (dict[str, str]) - Optional - A dictionary of IPP job attributes. ### Response #### Success Response (200) - **job_id** (int) - The ID of the newly created print job. ### Request Example ```python import cups conn = cups.Connection() job_id = conn.printFiles( "HP_Color", ["/tmp/cover.pdf", "/tmp/body.pdf", "/tmp/appendix.pdf"], "Full Report", {"media": "Letter", "sides": "two-sided-long-edge"} ) print(f"Job {job_id} submitted with 3 documents") ``` ``` -------------------------------- ### conn.acceptJobs(name) / conn.rejectJobs(name, reason) Source: https://context7.com/openprinting/pycups/llms.txt Controls whether a printer queue accepts new jobs. Rejection can include a reason. ```APIDOC ## conn.acceptJobs(name) / conn.rejectJobs(name, reason) ### Description Accepts or rejects new jobs for a printer queue. ### Parameters * **name** (str) - The name of the printer. * **reason** (str) - Optional. The reason for rejecting jobs. ``` -------------------------------- ### Manage Server-Wide CUPS Settings Source: https://context7.com/openprinting/pycups/llms.txt Retrieves and modifies server-wide CUPS settings. Requires root privileges. ```python import cups conn = cups.Connection() cups.setUser("root") settings = conn.adminGetServerSettings() print(settings) # {'BrowseLocalProtocols': 'dnssd', 'DefaultEncryption': 'Required', ...} # Enable remote admin settings[cups.CUPS_SERVER_REMOTE_ADMIN] = "1" settings[cups.CUPS_SERVER_SHARE_PRINTERS] = "1" conn.adminSetServerSettings(settings) ``` -------------------------------- ### Set Simple Password Callback Source: https://context7.com/openprinting/pycups/llms.txt Registers a callback function invoked when authentication is required. The callback receives a prompt string and must return a password or `None` to abort the operation. ```python import cups, getpass def ask_password(prompt): return getpass.getpass(prompt) cups.setPasswordCB(ask_password) conn = cups.Connection() ``` -------------------------------- ### Fetch Server PPD Source: https://context7.com/openprinting/pycups/llms.txt Retrieves a named PPD file from the CUPS server and loads it into a PPD object. The temporary PPD file is deleted after loading. ```python import cups conn = cups.Connection() ppds = conn.getPPDs(ppd_make="HP", limit=1) ppd_name = next(iter(ppds)) path = conn.getServerPPD(ppd_name) ppd_obj = cups.PPD(path) ``` -------------------------------- ### conn.printFile Source: https://context7.com/openprinting/pycups/llms.txt Submits a single file for printing. ```APIDOC ## conn.printFile(printer, filename, title, options) ### Description Submit a single file for printing. ### Parameters #### Path Parameters - **printer** (str) - Required - The name of the printer. - **filename** (str) - Required - The path to the file to print. - **title** (str) - Required - The title of the print job. #### Query Parameters - **options** (dict[str, str]) - Optional - A dictionary of IPP job attributes. ### Response #### Success Response (200) - **job_id** (int) - The ID of the newly created print job. ### Request Example ```python import cups conn = cups.Connection() try: job_id = conn.printFile( "LaserJet", "/home/user/report.pdf", "Monthly Report", {"media": "A4", "sides": "two-sided-long-edge", "number-up": "2"} ) print(f"Submitted as job {job_id}") except cups.IPPError as (status, desc): print(f"IPP error {status}: {desc}") ``` ``` -------------------------------- ### List All Printer Queues Source: https://context7.com/openprinting/pycups/llms.txt Retrieve a dictionary of all printer queues using `conn.getPrinters()`. Each entry includes printer state, reasons, device URI, and type. ```python import cups conn = cups.Connection() printers = conn.getPrinters() for name, attrs in printers.items(): state = attrs.get("printer-state", 0) state_str = {3: "idle", 4: "processing", 5: "stopped"}.get(state, "?") reasons = attrs.get("printer-state-reasons", []) print(f" {name}: {state_str}, reasons={reasons}") print(f" device-uri: {attrs.get('device-uri')}") ``` -------------------------------- ### conn.getPPD3(name, modtime, filename) Source: https://context7.com/openprinting/pycups/llms.txt Fetches a PPD file with cache checking. Returns a tuple containing HTTP status, modification time, and filename. If the cached file is current, the status will be cups.HTTP_NOT_MODIFIED. ```APIDOC ## conn.getPPD3(name, modtime, filename) ### Description Fetches a PPD file with cache checking. Returns a 3-tuple of HTTP status, modification time, and filename. If the cached file is still current, status is `cups.HTTP_NOT_MODIFIED`. ### Parameters * **name** (str) - The name of the PPD to fetch. * **modtime** (int) - The modification time of the cached PPD. * **filename** (str) - The filename of the cached PPD. ### Returns * **status** (int) - The HTTP status code. * **modtime** (int) - The modification time of the PPD. * **filename** (str) - The path to the PPD file. ``` -------------------------------- ### Accept or Reject New Jobs (Python) Source: https://context7.com/openprinting/pycups/llms.txt Controls whether a printer queue accepts new print jobs. Can specify a reason for rejection. Useful for managing job flow during maintenance or specific conditions. ```python import cups conn = cups.Connection() conn.rejectJobs("LaserJet", reason="Out of paper") conn.acceptJobs("LaserJet") ``` -------------------------------- ### Mark PPD Option Choices and Check Conflicts Source: https://context7.com/openprinting/pycups/llms.txt This code marks default options and specific choices for 'PageSize' and 'Duplex' in a PPD file, then checks for resulting conflicts. Ensure a PPD file for 'LaserJet' is available. ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) ppd.markDefaults() ppd.markOption("PageSize", "A4") ppd.markOption("Duplex", "DuplexNoTumble") print("Conflicts after marking:", ppd.conflicts()) ``` -------------------------------- ### conn.getPPD Source: https://context7.com/openprinting/pycups/llms.txt Fetches a printer's PPD file and returns the path to a temporary file containing its content. ```APIDOC ## conn.getPPD(name) ### Description Fetch a printer's PPD to a temp file. Returns the path to a temporary file containing the PPD. ### Parameters #### Path Parameters - **name** (str) - Required - The name of the printer. ### Response #### Success Response (200) - **ppd_path** (str) - The path to the temporary file containing the PPD. ### Request Example ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") print(f"PPD stored at: {ppd_path}") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) # clean up when done ``` ``` -------------------------------- ### conn.createJob Source: https://context7.com/openprinting/pycups/llms.txt Creates an empty streaming job, intended for use with startDocument, writeRequestData, and finishDocument. ```APIDOC ## conn.createJob(printer, title, options) ### Description Create empty streaming job. Creates a job without data; use with `startDocument`, `writeRequestData`, and `finishDocument` for streaming. ### Parameters #### Path Parameters - **printer** (str) - Required - The name of the printer. - **title** (str) - Required - The title of the print job. #### Query Parameters - **options** (dict[str, str]) - Optional - A dictionary of IPP job attributes. ### Response #### Success Response (200) - **job_id** (int) - The ID of the newly created streaming job. ### Request Example ```python import cups conn = cups.Connection() job_id = conn.createJob("LaserJet", "Streamed Document", {"media": "A4"}) conn.startDocument( "LaserJet", job_id, "page1.pdf", cups.CUPS_FORMAT_PDF, 1 # last_document ) with open("/tmp/page1.pdf", "rb") as f: data = f.read() conn.writeRequestData(data, len(data)) conn.finishDocument("LaserJet") print(f"Streaming job {job_id} complete") ``` ``` -------------------------------- ### Open Connection to CUPS Server Source: https://context7.com/openprinting/pycups/llms.txt Constructs a `cups.Connection` object to interact with a CUPS server. Defaults can be set using `cups.setServer`, `cups.setUser`, and `cups.setEncryption` before instantiation. Handles `RuntimeError` on connection failure. ```python import cups # Set connection defaults before constructing (optional) cups.setServer("localhost") cups.setUser("admin") cups.setEncryption(cups.HTTP_ENCRYPT_IF_REQUESTED) # Simple password callback def pw_callback(prompt, conn, method, resource, context): return "secret" # return None to abort cups.setPasswordCB2(pw_callback) try: conn = cups.Connection() print(repr(conn)) # except RuntimeError as e: print("Cannot connect:", e) # Connect to a remote server explicitly remote = cups.Connection(host="printserver.example.com", port=631, encryption=cups.HTTP_ENCRYPT_ALWAYS) ``` -------------------------------- ### Print Test Page Source: https://context7.com/openprinting/pycups/llms.txt Submits a test page to a printer. Can use a default or custom file and format. ```python import cups conn = cups.Connection() job_id = conn.printTestPage("LaserJet") print(f"Test page submitted as job {job_id}") # Custom file job_id = conn.printTestPage("LaserJet", file="/tmp/custom_test.ps", title="Custom Test", format="application/postscript") ``` -------------------------------- ### Add or Modify Printer Queue (Python) Source: https://context7.com/openprinting/pycups/llms.txt Adds a new printer queue or modifies an existing one. Requires printer name, PPD file, info, location, and device URI. After adding, it enables the printer and accepts jobs. ```python import cups conn = cups.Connection() cups.setUser("root") conn.addPrinter( "NewLaserJet", ppdname="HP/hp-laserjet_p1005-hpijs.ppd", info="HP LaserJet P1005", location="Room 101", device="usb://HP/LaserJet%20P1005" ) conn.enablePrinter("NewLaserJet") conn.acceptJobs("NewLaserJet") print("Printer added and enabled") ``` -------------------------------- ### createSubscription Source: https://context7.com/openprinting/pycups/llms.txt Creates a new event subscription on the CUPS server. ```APIDOC ## createSubscription(uri, events, job_id=None, recipient_uri=None, lease_duration=None, time_interval=None, user_data=None) ### Description Creates a new event subscription on the CUPS server. ### Method `conn.createSubscription(uri, events, job_id, recipient_uri, lease_duration, time_interval, user_data)` ### Parameters - **uri** (str) - The CUPS server URI. - **events** (list) - A list of event names to subscribe to (e.g., 'printer-state-changed'). - **job_id** (int, optional) - The job ID to subscribe to events for. - **recipient_uri** (str, optional) - The URI to send notifications to. - **lease_duration** (int, optional) - The duration of the subscription in seconds. - **time_interval** (int, optional) - The interval for notifications in seconds. - **user_data** (str, optional) - User-defined data to include in notifications. ### Request Example ```python import cups conn = cups.Connection() sub_id = conn.createSubscription( "ipp://localhost/", events=["printer-state-changed", "job-state-changed", "printer-added", "printer-deleted"], lease_duration=3600 ) print(f"Subscription ID: {sub_id}") ``` ### Response #### Success Response (int) - Returns the ID of the newly created subscription. ``` -------------------------------- ### adminGetServerSettings / adminSetServerSettings Source: https://context7.com/openprinting/pycups/llms.txt Retrieves and modifies server-wide CUPS settings. ```APIDOC ## adminGetServerSettings() / adminSetServerSettings(settings) ### Description Retrieves and modifies server-wide CUPS settings. ### Method `conn.adminGetServerSettings()` `conn.adminSetServerSettings(settings)` ### Parameters - **settings** (dict) - A dictionary containing the server settings to apply. ### Request Example ```python import cups conn = cups.Connection() cups.setUser("root") settings = conn.adminGetServerSettings() print(settings) # {'BrowseLocalProtocols': 'dnssd', 'DefaultEncryption': 'Required', ...} # Enable remote admin settings[cups.CUPS_SERVER_REMOTE_ADMIN] = "1" settings[cups.CUPS_SERVER_SHARE_PRINTERS] = "1" conn.adminSetServerSettings(settings) ``` ### Response #### Success Response (`adminGetServerSettings` returns dict, `adminSetServerSettings` returns None) - Returns a dictionary of server settings or None. ``` -------------------------------- ### Connect to a Destination Source: https://context7.com/openprinting/pycups/llms.txt Connect directly to a printer's URI using `cups.connectDest`. This is useful for network printers. The function returns a `(Connection, resource)` tuple. ```python import cups dests_found = [] def collect(user_data, flags, dest): user_data.append(dest) return 1 cups.enumDests(collect, user_data=dests_found, msec=3000) if dests_found: target = dests_found[0] conn, resource = cups.connectDest(target, lambda ud, f, d: 1) print(f"Connected, resource: {resource}") ``` -------------------------------- ### cups.connectDest(dest, cb, flags, msec, user_data) Source: https://context7.com/openprinting/pycups/llms.txt Opens a direct connection to a destination's printer URI, which is particularly useful for network printers. It returns a tuple containing the connection object and resource. ```APIDOC ## cups.connectDest(dest, cb, flags, msec, user_data) ### Description Opens a connection directly to the destination's printer URI (useful for network printers). Returns a `(Connection, resource)` tuple. ### Parameters - **dest** (Destination) - The destination to connect to. - **cb** (callable) - Callback function. - **flags** (int) - Flags for the connection. - **msec** (int) - Timeout in milliseconds. - **user_data** (any) - User-provided data. ### Returns - **(Connection, resource)** - A tuple containing the connection object and resource identifier. ### Example ```python import cups dests_found = [] def collect(user_data, flags, dest): user_data.append(dest) return 1 cups.enumDests(collect, user_data=dests_found, msec=3000) if dests_found: target = dests_found[0] conn, resource = cups.connectDest(target, lambda ud, f, d: 1) print(f"Connected, resource: {resource}") ``` ``` -------------------------------- ### Fetch Printer PPD to Temp File Source: https://context7.com/openprinting/pycups/llms.txt Retrieves the Printer Description (PPD) file for a given printer and saves it to a temporary file. The function returns the path to this temporary file. Remember to clean up the file using `os.unlink` after use. ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") print(f"PPD stored at: {ppd_path}") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) # clean up when done ``` -------------------------------- ### Connection.getClasses() Source: https://context7.com/openprinting/pycups/llms.txt Retrieves a dictionary of printer classes. The value associated with each class name is either a list of member queue names for local classes or a URI string for remote classes. ```APIDOC ## conn.getClasses() ### Description Returns a dict keyed by class name. The value is either a list of member queue names (local class) or a URI string (remote class). ### Returns - **dict** - A dictionary where keys are class names and values are lists of member queue names or URIs. ### Example ```python import cups conn = cups.Connection() classes = conn.getClasses() for cls_name, members in classes.items(): print(f"Class {cls_name}: {members}") ``` ``` -------------------------------- ### Load PPD File Source: https://context7.com/openprinting/pycups/llms.txt Parses a PPD file from disk, providing access to printer options, groups, constraints, and attributes. The PPD file is fetched from the server and then deleted. ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) # Mark all options at their defaults ppd.markDefaults() ``` -------------------------------- ### List Printer Classes Source: https://context7.com/openprinting/pycups/llms.txt Retrieve a dictionary of printer classes using `conn.getClasses()`. Values are lists of member queue names for local classes or URIs for remote classes. ```python import cups conn = cups.Connection() classes = conn.getClasses() for cls_name, members in classes.items(): print(f"Class {cls_name}: {members}") ``` -------------------------------- ### Localize IPP Reason String Source: https://context7.com/openprinting/pycups/llms.txt This snippet demonstrates how to localize an IPP reason string using the PPD object's localization capabilities. It requires a PPD file for 'LaserJet' and calls `ppd.localize()` first. ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) ppd.localize() local_reason = ppd.localizeIPPReason("toner-low", "text") if local_reason: print(f"Localized reason: {local_reason}") ``` -------------------------------- ### ppd.markOption(option, choice) Source: https://context7.com/openprinting/pycups/llms.txt Marks a specific option and choice within a PPD file. This is useful for setting printer configurations programmatically before writing or processing the PPD. ```APIDOC ## ppd.markOption(option, choice) — Mark an option choice ### Description Marks a specific option and choice within a PPD file. This is useful for setting printer configurations programmatically before writing or processing the PPD. ### Parameters - **option** (string) - The keyword of the option to mark. - **choice** (string) - The keyword of the choice to mark for the given option. ### Request Example ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) ppd.markDefaults() ppd.markOption("PageSize", "A4") ppd.markOption("Duplex", "DuplexNoTumble") print("Conflicts after marking:", ppd.conflicts()) ``` ``` -------------------------------- ### cups.setServer Source: https://context7.com/openprinting/pycups/llms.txt Sets or retrieves the default hostname for new `Connection` objects. ```APIDOC ## cups.setServer(server) ### Description Sets the default hostname for new `Connection` objects. ### Method Setter ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```python import cups cups.setServer("cups.internal.example.com") print(cups.getServer()) # "cups.internal.example.com" conn = cups.Connection() # connects to cups.internal.example.com ``` ### Response #### Success Response (200) None #### Response Example None ``` ```APIDOC ## cups.getServer() ### Description Retrieves the default hostname for new `Connection` objects. ### Method Getter ### Parameters None ### Request Example ```python import cups cups.setServer("cups.internal.example.com") print(cups.getServer()) # "cups.internal.example.com" conn = cups.Connection() # connects to cups.internal.example.com ``` ### Response #### Success Response (200) - **server** (string) - The default server hostname #### Response Example ``` "cups.internal.example.com" ``` ``` -------------------------------- ### conn.getPPDs(...) Source: https://context7.com/openprinting/pycups/llms.txt Lists all available PPDs, supporting various filter keyword arguments. Returns a dictionary keyed by PPD name. ```APIDOC ## conn.getPPDs(...) ### Description Lists all available PPDs, supporting many filter kwargs. Returns a dict keyed by PPD name (`ppd-name`). ### Parameters * **kwargs** - Supports many filter keyword arguments such as `ppd-make`, `ppd-model`, etc. ### Returns * **dict** - A dictionary where keys are PPD names and values are dictionaries of PPD attributes. ``` -------------------------------- ### ppd.writeFd(fd) / ppd.emitString(section, limit) Source: https://context7.com/openprinting/pycups/llms.txt Serializes a PPD file or a specific section of it. `writeFd` writes the PPD to a file descriptor, while `emitString` returns a section as a string. ```APIDOC ## ppd.writeFd(fd) / ppd.emitString(section, limit) — Serialize a PPD ### Description Serializes a PPD file or a specific section of it. `writeFd` writes the PPD to a file descriptor, while `emitString` returns a section as a string. ### Parameters - **fd** (integer) - A file descriptor to write the PPD to (for `writeFd`). - **section** (integer) - The PPD section to emit (e.g., `cups.PPD_ORDER_JCL`) (for `emitString`). - **limit** (integer) - The maximum number of bytes to emit (for `emitString`). ### Request Example ```python import cups, os, tempfile conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) ppd.markOption("PageSize", "A4") # Write modified PPD to a temp file fd, out_path = tempfile.mkstemp(suffix=".ppd") ppd.writeFd(fd) os.close(fd) print(f"Modified PPD written to {out_path}") # Or emit a section as a string header_str = ppd.emitString(cups.PPD_ORDER_JCL, 0) print(header_str[:200]) ``` ``` -------------------------------- ### Transfer CUPS Server Files Source: https://context7.com/openprinting/pycups/llms.txt Fetches or uploads CUPS server configuration and log files. Requires root privileges for sensitive files. ```python import cups conn = cups.Connection() cups.setUser("root") # Download cupsd.conf conn.getFile("/admin/conf/cupsd.conf", filename="/tmp/cupsd.conf.bak") # Modify and re-upload with open("/tmp/cupsd.conf.bak") as f: data = f.read().replace("LogLevel warn", "LogLevel debug") with open("/tmp/cupsd.conf.new", "w") as f: f.write(data) conn.putFile("/admin/conf/cupsd.conf", filename="/tmp/cupsd.conf.new") ``` -------------------------------- ### Submit Multiple Files as One Job Source: https://context7.com/openprinting/pycups/llms.txt Submits a list of files to be printed as a single job. The 'options' dictionary can specify job attributes. ```python import cups conn = cups.Connection() job_id = conn.printFiles( "HP_Color", ["/tmp/cover.pdf", "/tmp/body.pdf", "/tmp/appendix.pdf"], "Full Report", {"media": "Letter", "sides": "two-sided-long-edge"} ) print(f"Job {job_id} submitted with 3 documents") ``` -------------------------------- ### conn.getJobs Source: https://context7.com/openprinting/pycups/llms.txt Lists print jobs, returning a dictionary keyed by job ID with each value being a dictionary of job attributes. ```APIDOC ## conn.getJobs(which_jobs, my_jobs, limit, first_job_id, requested_attributes) ### Description Returns a dict keyed by job ID. Each value is a dict of job attributes. ### Parameters #### Query Parameters - **which_jobs** (str) - Optional - Specifies which jobs to retrieve (e.g., "not-completed", "completed"). - **my_jobs** (bool) - Optional - If True, only retrieve jobs for the current user. - **limit** (int) - Optional - The maximum number of jobs to return. - **first_job_id** (int) - Optional - The ID of the first job to return. - **requested_attributes** (list[str]) - Optional - A list of specific job attributes to retrieve. ### Request Example ```python import cups conn = cups.Connection() # All active jobs active = conn.getJobs(which_jobs="not-completed") for jid, attrs in active.items(): print(f" Job {jid}: {attrs.get('job-name')} state={attrs.get('job-state')} user={attrs.get('job-originating-user-name')}") # Completed jobs for the current user only done = conn.getJobs(which_jobs="completed", my_jobs=True, limit=20) # Custom attributes custom = conn.getJobs( requested_attributes=["job-id", "job-name", "job-state", "time-at-creation"] ) ``` ``` -------------------------------- ### Set Printer Access Control (Python) Source: https://context7.com/openprinting/pycups/llms.txt Manages which users are allowed or denied access to a printer queue. Use 'all' to remove restrictions. Essential for securing sensitive printers. ```python import cups conn = cups.Connection() # Only allow specific users conn.setPrinterUsersAllowed("SecurePrinter", ["alice", "bob", "carol"]) # Deny specific users conn.setPrinterUsersDenied("LaserJet", ["baduser"]) # Remove restrictions conn.setPrinterUsersAllowed("LaserJet", ["all"]) ``` -------------------------------- ### ppd.findOption(option) Source: https://context7.com/openprinting/pycups/llms.txt Looks up a PPD option by its keyword. Returns an Option object if found, otherwise None. This allows inspection of option details like UI type and available choices. ```APIDOC ## ppd.findOption(option) — Look up an option by keyword ### Description Looks up a PPD option by its keyword. Returns an Option object if found, otherwise None. This allows inspection of option details like UI type and available choices. ### Parameters - **option** (string) - The keyword of the option to find. ### Returns - `cups.Option` object or `None` if the option is not found. ### Request Example ```python import cups, os conn = cups.Connection() ppd_path = conn.getPPD("LaserJet") ppd = cups.PPD(ppd_path) os.unlink(ppd_path) opt = ppd.findOption("PageSize") if opt: print(f"PageSize UI: {opt.ui}") print(f"Choices: {[c['choice'] for c in opt.choices]}") print(f"Default: {opt.defchoice}") ``` ```