def printer_watchdog():
    DEFAULT_LOCALE_ENCODING = get_system_encoding()
    print win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL)  # get local printers
    print win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS)  # get printers which other computer shared

    default_printer_name = win32print.GetDefaultPrinter()

    printer = win32print.OpenPrinter(default_printer_name)
    print win32print.GetPrinter(printer)

    jobs_list = list()
    total_seconds = 60 * 5  # reset after 60*5 seconds
    sleep_seconds = 10
    times = total_seconds / sleep_seconds
    current_times = 0
    while True:
        jobs = win32print.EnumJobs(printer, 0, 3, 1)
        # 0 is location of first job,
        # 3 is number of jobs to enumerate,
        # 1 is job info level, can be 1(win32print.JOB_INFO_1), 2, 3. 3 is reserved, 1 and 2 can NOT get job status, :(
        if len(jobs) >= 1:
            for job in jobs:
                print job.get('pUserName'), job.get('Submitted'), job.get('pMachineName'), \
                    job.get('pDocument').decode(DEFAULT_LOCALE_ENCODING)
                jobs_list.append(job.get('JobId', -1))
            if any([jid in jobs_list for jid in (jobs[0].get('JobId'), jobs[-1].get('JobId'))]):
                current_times += 1
            if current_times > times:
                print "printer need to be reset, ... "
                reset_printer()
                jobs_list = []  # make sure there are not same job id in list
                current_times = 0
        print 'looks good'
        time.sleep(sleep_seconds)
Exemple #2
0
def printer_watchdog():
    print win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL)  # get local printers
    print win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS)  # get printers which other computer shared

    default_printer_name = win32print.GetDefaultPrinter()

    printer = win32print.OpenPrinter(default_printer_name)
    print win32print.GetPrinter(printer)

    jobs_list = list()
    total_seconds = 60 * 5  # reset after 60*5 seconds, see 'known issue 2' in this file.
    sleep_seconds = 10
    times = total_seconds / sleep_seconds
    current_times = 0
    while True:
        jobs = win32print.EnumJobs(printer, 0, 3, 1)
        # except: pywintypes.error: (1722, 'EnumJobs', 'RPC 服务器不可用。'), ignored this except
        # 0 is location of first job,
        # 3 is number of jobs to enumerate,
        # 1 is job info level, can be 1(win32print.JOB_INFO_1), 2, 3. 3 is reserved, 1 and 2 can NOT get job status, :(
        if len(jobs) >= 1:
            for job in jobs:
                filename = job.get('pDocument')
                job_id = job.get('JobId', md5(filename).hexdigest())

                job_status = job.get('Status', 0)
                if job_status in [0x00000002, 0x00000004, 0x00000800]:  # JOB_STATUS_ERROR
                    """
                    Refers:
                        https://docs.microsoft.com/en-us/windows/desktop/printdocs/job-info-2
                        ~\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\WinSDK\Include\WinSpool.h
                    """
                    print "printer need to be reset, ... "
                    reset_printer()
                    jobs_list = []  # make sure there are not same job id in list
                    current_times = 0

                print "Current job: ", job_id, job.get('pUserName'), job.get('Submitted'), job.get(
                    'pMachineName'), filename, "[ %d/%d ]" % (times, current_times + 1)
                jobs_list.append(job_id)

            # if any([jid in jobs_list for jid in (jobs[0].get('JobId'), jobs[-1].get('JobId'))]):
            #     current_times += 1
            if Counter(jobs_list).most_common(1)[0][1] > 1:
                current_times += 1

            if current_times > times:
                """ KNOWN ISSUE 2:
                It will reset when a document sends lots of pages to printer. 
                This script may reset printer before job finished which is not expected.  
                """
                print "printer need to be reset, ... "
                reset_printer()
                jobs_list = []  # make sure there are not same job id in list
                current_times = 0
        else:
            jobs_list = []
            current_times = 0
            print 'looks good, keep watching ...'
        time.sleep(sleep_seconds)
def printer_watchdog():
    # DEFAULT_LOCALE_ENCODING = get_system_encoding()
    print win32print.EnumPrinters(
        win32print.PRINTER_ENUM_LOCAL)  # get local printers
    print win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS
                                  )  # get printers which other computer shared

    default_printer_name = win32print.GetDefaultPrinter()

    printer = win32print.OpenPrinter(default_printer_name)
    print win32print.GetPrinter(printer)

    jobs_list = list()
    total_seconds = 60 * 5  # reset after 60*5 seconds, see 'known issue 2' in this file.
    sleep_seconds = 10
    times = total_seconds / sleep_seconds
    current_times = 0
    while True:
        jobs = win32print.EnumJobs(printer, 0, 3, 1)
        # 0 is location of first job,
        # 3 is number of jobs to enumerate,
        # 1 is job info level, can be 1(win32print.JOB_INFO_1), 2, 3. 3 is reserved, 1 and 2 can NOT get job status, :(
        if len(jobs) >= 1:
            for job in jobs:
                filename = job.get('pDocument')
                job_id = job.get('JobId', md5(filename).hexdigest())
                print "Current job: ", job_id, job.get('pUserName'), job.get(
                    'Submitted'), job.get(
                        'pMachineName'), filename, "[ %d/%d ]" % (
                            times, current_times + 1)
                jobs_list.append(job_id)

            # if any([jid in jobs_list for jid in (jobs[0].get('JobId'), jobs[-1].get('JobId'))]):
            #     current_times += 1
            if Counter(jobs_list).most_common(1)[0][1] > 1:
                current_times += 1

            if current_times > times:
                """ KNOWN ISSUE 2:
                It will reset when a document sends lots of pages to printer. 
                This script may reset printer before job finished which is not expected.  
                """
                print "printer need to be reset, ... "
                reset_printer()
                jobs_list = []  # make sure there are not same job id in list
                current_times = 0
        else:
            jobs_list = []
            current_times = 0
            print 'looks good, keep watching ...'
        time.sleep(sleep_seconds)
Exemple #4
0
def printerList():
	printerList = []
	for printerItem in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 1):
	 	flags, desc, name, comment = printerItem
	 	printerList.append(name.encode('utf-8'))

	return printerList
    def cambiaImpresora(self):
        # self.tabWidget.setCurrentIndex(1)
        self.listaDeImpresoras.setEnabled(True)

        for (a, b, name,
             d) in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL):
            self.listaDeImpresoras.addItem(name)
Exemple #6
0
def SendToBP33(fn_bpl, req_confirm = True):

    printers = win32print.EnumPrinters(2)
    for p in printers:
        if p[3] == 'BBP33':
            printer_name = p[2]
            #print('Found printer ' + printer_name)

    if (printer_name):
        cont = 'y'
        if(req_confirm):
            cont = input('Use ' + printer_name + ' to print labels? [y/n]\n')
        if (cont == 'y'):
            f_bpl = open(fn_bpl, "rb")
            hPrinter = win32print.OpenPrinter(printer_name)
            try:
              hJob = win32print.StartDocPrinter (hPrinter, 1, ("Cable labels", None, "RAW"))
              try:
                win32print.StartPagePrinter (hPrinter)
                win32print.WritePrinter (hPrinter, f_bpl.read())
                win32print.EndPagePrinter (hPrinter)
              finally:
                win32print.EndDocPrinter (hPrinter)
            finally:
              win32print.ClosePrinter (hPrinter)
            f_bpl.close()
        else:
def load_config():
    print(__file__, "当前操作系统--", OS)
    if OS == "Linux":
        home = os.environ['HOME']
        config_path = os.path.join(home, 'printer/config.json')

    elif OS == "Windows":
        config_path = "c:/printer/config.json"
        import win32print
        for printer in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL):
            PRINTER_LIST.append(printer[2])
    else:
        print(__file__, "不支持的平台")
        return False
    # config 是一个字典
    config = {}
    res = db.execute('SELECT * FROM KEY_VALUE')
    if not res:
        return False
    for i in res:
        config[i[0]] = i[1]
    # 并对参数进行检查
    config["os"] = OS
    config["config_path"] = config_path
    return config
Exemple #8
0
    def ReadInf(self, infPath):
        if infPath is None:
            return False
        modelLine = []
        self.modelName = []
        try:
            file = open(infPath, 'r')
        except IOError:
            QMessageBox.warning(self, 'Warning', '读取INF路径失败')
            return
        pattern_list = "(PS\")|(PCL6\")|(PS\))|(PCL6\))"
        pattern = re.compile(pattern_list)  # 利用正则寻找model名
        for line in file.readlines():
            result = re.search(pattern, line)
            if result:
                modelLine.append(line)
        file.close()
        for i in range(len(modelLine)):
            tempName = str(modelLine[i]).split('"')  # 筛选model名
            if tempName[1] in self.modelName:
                continue
            else:
                self.modelName.append(tempName[1])  # 将获取的model名存入列表

        self.comboBox_2.clear()  # 添加前清空组合框内容
        for i in self.modelName:  # 循环添加组合框项目
            self.comboBox_2.addItem(i)
        print(self.modelName)
        print_name_tuple = win32print.EnumPrinters(
            win32print.PRINTER_ENUM_NAME, None, 4)
        for i in range(len(print_name_tuple)):
            print(print_name_tuple[i].get("pPrinterName"))
def GetListeImprimantes():
    listeImprimantes = []
    try:
        for a, b, nom, c in win32print.EnumPrinters(2):
            listeImprimantes.append(nom)
    except Exception, err:
        print "Erreur dans recuperation de la liste des imprimantes : ", err
Exemple #10
0
    def set_ui(self):
        printers = win32print.EnumPrinters(2)
        current_printer = win32print.GetDefaultPrinter()
        printers_list = [i[2] for i in printers]
        self.current_printer_label = QLabel("默认打印机")
        self.current_printer = QLineEdit(current_printer)
        self.current_printer.setReadOnly(True)
        self.current_printer.setStyleSheet("background:#f0f0f0")
        self.printer_label = QLabel("选择打印机")
        self.printer_name = QComboBox()
        for i in printers_list:
            self.printer_name.addItem(i)
        self.printer_name.currentIndexChanged.connect(self.change_printer)
        self.confirm_bnt = QPushButton("确定")
        # self.cancel_bnt = QPushButton("取消")
        self.confirm_bnt.clicked.connect(self.choose_printer)

        self.layout = QVBoxLayout()
        self.layout.addWidget(self.printer_label)
        self.layout.addWidget(self.printer_name)
        self.layout.addWidget(self.current_printer_label)
        self.layout.addWidget(self.current_printer)
        self.layout.addStretch()
        self.layout.addWidget(self.confirm_bnt)
        self.setLayout(self.layout)
Exemple #11
0
 def on_bt_about_clicked(self):
     """
     ABOUT ME and selects the zebra printer
     """
     xprinters = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None, 1)
     print (xprinters)
     printers = win32print.EnumPrinters(5)
     current = printers[-1]
     name = current[-2]
     self.name = name 
     self.printer = printers
     print (printers)
     print(current)
     print(name)
     
     QMessageBox.about(self, "copyright_A_TMHMATOS", "creator αμανατιδης αλκης \nemail:[email protected] ")
Exemple #12
0
def list_printers():
    printer_info = win32print.EnumPrinters(
        win32print.PRINTER_ENUM_LOCAL | win32print.PRINTER_ENUM_CONNECTIONS)
    printer_names = [
        name for (flags, description, name, comment) in printer_info
    ]
    return printer_names
Exemple #13
0
def check_printer():
    myprinter = None
    A = win32print.EnumPrinters(win32print.PRINTER_ENUM_NAME, None, 2)
    for i in range(len(A)):
        if A[i]['pPrinterName'] == tempprinter:
            return True
    return False
Exemple #14
0
 def _default_printers(self):
     if not PRINTER_AVAILABLE:
         return []
     return [
         p[2]
         for p in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL)
     ]
Exemple #15
0
    def PrinterList(self):

        # returns a list of dicts.
        # this gets the default printer
        tmpdic = {}
        DefPName = win32print.GetDefaultPrinter()

        # Get the default printer firstso we can add this to the list of printers

        for pt in ptypelist:

            try:

                for (Flags, pDescription, pName,
                     pComment) in list(win32print.EnumPrinters(pt[0], None,
                                                               1)):
                    tmpdic = {}
                    tmpdic['PType'] = pt[1]
                    tmpdic['Flags'] = Flags
                    tmpdic['Description'] = pDescription
                    #test for if this is the default printer
                    if pName == DefPName:
                        tmpdic['DefPrinter':True]
                    else:
                        tmpdic['DefPrinter':False]
                    tmpdic['Name'] = pName
                    tmpdic['Comment'] = pComment
                    self.PList.append(tmpdic)
            except:
                pass  #no printers of this type so don't add anything

        return self.PList  #list of installed printers
Exemple #16
0
def print_job_checker():
    server = socket.gethostname()
    while True:
        jobs = []
        for p in win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL, None,
                                         1):
            flags, desc, name, comment = p
            phandle = win32print.OpenPrinter(name)
            print_jobs = win32print.EnumJobs(phandle, 0, -1, 1)
            if print_jobs:
                jobs.extend(list(print_jobs))
            for job in print_jobs:

                document = job["pDocument"]
                username = job['pUserName']
                identity = job['JobId']
                jobstate = job['Status']
                machinename = job['pMachineName'].replace("\\\\", "")
                pTime = datetime.datetime.now().isoformat()
                today = datetime.date.today().isoformat()
                Pages = job['TotalPages']
                printstr = "[Server:" + server + "],[Who:" + username + "],[Computer:" + machinename + "],[Print Time:" + pTime + "],[JobID:" + str(
                    identity) + "]"
                print(printstr)
            win32print.ClosePrinter(phandle)
        time.sleep(0.5)
Exemple #17
0
 def geraListaImpressoras(self):
     global listaImpressoras
     lista = win32print.EnumPrinters(win32print.PRINTER_ENUM_LOCAL
                                     | win32print.PRINTER_ENUM_CONNECTIONS)
     listaImpressoras = [
         name for (flags, description, name, comment) in lista
     ]
     listaImpressoras = sorted(listaImpressoras)
Exemple #18
0
def get_printer_list():
    printers = win32print.EnumPrinters(2)
    def_printer = win32print.GetDefaultPrinter()
    p_list = [def_printer]
    for p in printers:
        if not p[1].split(',')[0] == def_printer:
            p_list.append(p[1].split(",")[0])
    return p_list
def EnviarImpresion(namepdf, impresoraselect):
    impresoras = [
        x[2]
        for x in win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS)
    ]
    win32print.SetDefaultPrinter(impresoras[int(impresoraselect)])
    os.startfile(namepdf, "print")
    return JsonResponse({'msg': True})
Exemple #20
0
def getPrinter():
    default_printer = win32print.GetDefaultPrinter()
    printer_lst = list(win32print.EnumPrinters(2))
    all_printers = [one_tuple[1].split(',')[0] for one_tuple in printer_lst]
    info = "本机连接的打印机:%s\n" \
           "当前默认打印机:%s" % (all_printers, default_printer)
    logger.info(info)
    return (all_printers, default_printer)
Exemple #21
0
 def EnumPrinter(self):
     handle = win32print.OpenPrinter(self.printer_name)
     win32print.GetPrinter(handle)
     win32print.ClosePrinter(handle)
     printers = []
     for p in win32print.EnumPrinters(2):
         printers.append(p[1].split(',')[0])
     return printers
Exemple #22
0
def viewAllPrinters():
    printers = win32print.EnumPrinters(2)
    default_printer = win32print.GetDefaultPrinter()
    for printer in printers:
        if printer[2] == default_printer:
            print("==> " + printer[2] + " <== Default")
        else:
            print("    " + printer[2])
    exit()
Exemple #23
0
def printPDF(
    filenamePDF,
    defaultFolder='requests',
    defaultPrinter='default'
):  # Check bin foler and PDFtoPrinter exists and on the expected location

    if os.path.exists('bin'):
        PDFtoPrinter = os.path.join(
            os.path.abspath('bin'),
            'PDFtoPrinter.exe')  # get he full path of the PDF file printer
        if not os.path.exists(PDFtoPrinter):
            logThis('Error : bin\\PDFtoPrinter.exe is missing')
            return False
    else:
        logThis('Error : bin folder is missing')
        return False

    if os.path.exists(
            defaultFolder
    ):  # Check if the defaultFolder exisit and the PDF file exists
        printFile = os.path.join(
            os.path.abspath(defaultFolder),
            filenamePDF)  # full path of the file to be printed
        if not os.path.exists(printFile):
            logThis('Error : %s\\%s is missing' % (defaultFolder, filenamePDF))
            return False
    else:
        logThis('Error : %s folder is missing' % defaultFolder)
        return False

    # Check printer
    if defaultPrinter == 'default':
        defaultPrinter = win32print.GetDefaultPrinter(
        )  # getthe default printer
        if defaultPrinter is None:
            logThis('Error : No default printer or no printer installed')
            return False
    else:
        if not defaultPrinter in win32print.EnumPrinters(
                5
        ):  # check if the default printer is in the list of installed printers
            logThis('Error : %s is not installed' % (defaultPrinter))
            return False

    try:
        logThis('sending %s to printer' % (filenamePDF))
        p = subprocess.Popen(
            [PDFtoPrinter, printFile],
            stdout=subprocess.PIPE,
            stderr=subprocess.PIPE
        )  # actual command for sending the PDF fiel to the printer
        stdout, stderr = p.communicate()
        return True
    except:
        return False

    return False
Exemple #24
0
 def list_printers(self):
     printer_list = [item[2] for item in win32print.EnumPrinters(2)]
     black_list = [
         'Fax', 'Send To OneNote 2013', 'Microsoft XPS Document Writer'
     ]
     for item in black_list:
         if item in printer_list:
             printer_list.remove(item)
     return printer_list
Exemple #25
0
    def get_printers(self):
        print_list = [self.pdf_printer_name]
        printers = list(win32print.EnumPrinters(2))

        for i in printers:
            if "pdf" not in i[2].lower():
                print_list.append(i[2])

        return print_list
Exemple #26
0
    def loadPrinters(self):
        """ This function create a list of available printers. """
        data = win32print.EnumPrinters(6)
        printer_list = []

        for row in data:
            printer_list.append(row[2])

        return printer_list
Exemple #27
0
 def get_status(self, **params):
     messages = []
     for printer in win32print.EnumPrinters(
             win32print.PRINTER_ENUM_NAME, None, 5):
         messages.append(printer["pPrinterName"])
     state = {
         "status": "connected",
         "messages": messages,
     }
     return state
Exemple #28
0
 def printerinfo(self):
     info = []
     printers = win32print.EnumPrinters(win32print.PRINTER_ENUM_NAME, None, 2)
     default = self.defaultPrinter()
     for i, printer in enumerate(printers):
         if default == printers[i]['pPrinterName']:
             info.append((printers[i]['pPrinterName'], printers[i]['pPortName'], printers[i]['cJobs'], self.IS_DEFAULT_PRINTER))
         else:
             info.append((printers[i]['pPrinterName'], printers[i]['pPortName'], printers[i]['cJobs'], self.NOT_DEFAULT_PRINTER))
     return info
def build_dict():
    global prdict
    lst = win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS +
                                  win32print.PRINTER_ENUM_LOCAL)
    prdict = {}
    for flags, description, name, comment in lst:
        prdict[name] = {}
        prdict[name]["flags"] = flags
        prdict[name]["description"] = description
        prdict[name]["comment"] = comment
def get_printer_list():
    list = []
    #Enum printers returns the list of printers available in the network
    printers = win32print.EnumPrinters(win32print.PRINTER_ENUM_CONNECTIONS +
                                       win32print.PRINTER_ENUM_LOCAL)
    for i in printers:

        list.append(i[2])

    return list