Search code examples
pythonprintingpycharmpywin32

Access denied when attempting to remove printer


def on_printer_button_clicked(self, button):
    for i in range(len(self.printer_buttons)):
        if button == self.printer_buttons[i]:
            pHandle = win32print.OpenPrinter(self.printers[i]['pPrinterName'])
    win32print.DeletePrinter(pHandle)
    return

So all I'm doing is opening the printer handle and calling the function Delete Printer, as you can see. Here's what I get in the console when I run the function:

uninstall_windowGUI.py", line 57, in on_printer_button_clicked
win32print.DeletePrinter(pHandle)
pywintypes.error: (5, 'DeletePrinter', 'Access is denied.')

I've tried running the IDE (Pycharm in Administrator mode, and still get the same issue. Any idea on how to move on? I'm kind of stuck until I can figure this out. (Also: I'm using Gtk and Gdk to create the interface, if that makes a differece.)


Solution

  • The documentation states that Printer handle must be opened for PRINTER_ACCESS_ADMINISTER. Something like this might work:

    PRINTER_DEFAULTS = {"DesiredAccess":win32print.PRINTER_ACCESS_ADMINISTER} 
    win32print.OpenPrinter(self.printers[i]['pPrinterName'], PRINTER_DEFAULTS)