Search code examples
pythonprintingpywin32

Using DeviceCapabilities with pywin32


I want to change the tray of a printer by using python. I try to use the following code to retrieve information about the printer and its values:

import win32print
x = win32print.DeviceCapabilities('Name of my printer', '192.168.x.x', DC_BINS)
print (x)

DC_BINS is supposed to give me a sequence of int. Each belongs to a different tray. However, when I try to run this, the program says that "DC_BINS" is not defined. What am I doing wrong? I am fairly new with python.


Solution

  • your code corrected:

    import win32print
    import win32con
    x = win32print.DeviceCapabilities('Name of my printer', '192.168.x.x', win32con.DC_BINS)
    print (x)
    

    code that lists all printers, local and remote, and theirs capabilities:

    import win32print
    from win32con import *
    
    DC_CONSTANTS = [
        DC_BINNAMES, DC_BINS, DC_COLLATE, DC_COLORDEVICE, DC_COPIES, DC_DRIVER,
        DC_DUPLEX, DC_ENUMRESOLUTIONS, DC_EXTRA, DC_FIELDS,
        DC_FILEDEPENDENCIES, DC_MAXEXTENT, DC_MEDIAREADY, DC_MEDIATYPENAMES,
        DC_MEDIATYPES, DC_MINEXTENT, DC_ORIENTATION, DC_NUP, DC_PAPERNAMES,
        DC_PAPERS, DC_PAPERSIZE, DC_PERSONALITY, DC_PRINTERMEM, DC_PRINTRATE, DC_PRINTRATEPPM,
        DC_PRINTRATEUNIT, DC_SIZE, DC_STAPLE, DC_TRUETYPE, DC_VERSION,
    ]
    
    
    def DC_INFO(constant):
        for a_global in globals().keys():
            if a_global.startswith("DC_") and globals().get(a_global) == constant:
                return a_global
        return "DC_UNKONWN"
    
    
    for printer in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS):
        print printer
        for constant in DC_CONSTANTS:
            try:
                x = win32print.DeviceCapabilities(printer[2], '', constant)
                print "\t", DC_INFO(constant), x
            except:
                pass
    

    I would recommend using an IDE for python, good IDE will mark unknown symbols and suggest where to import those from (like PyCharm does).