python - 如何调试作为服务运行的Python程序?

标签 python windows-10 pywin32

我有一个 python 脚本,在控制台中运行时运行良好。 但是,当使用 pywin32 使其作为服务运行时,该服务会安装并正常启动,但不会产生所需的输出。所以肯定出了什么问题——但我看不到发生了什么来找出原因。

<小时/>

该脚本执行以下操作:

  1. 在给定输入目录中搜索 *.csv 文件
  2. 如果未找到此类文件,则会等待 1 分钟。如果找到,则将其用作步骤 3 的输入。如果找到多个 csv 文件,则使用第一个。
  3. 对列的顺序进行一些转换
  4. 将转换后的内容写入输出 csv
  5. 将输入 csv 移至子目录并重命名。

我先给大家展示一下作为服务实现的版本的代码:

#!/usr/bin/env python3

import sys
import os
import csv
from pathlib import Path
import time
import win32service
import win32serviceutil
import win32event


def reorder_AT_csv(ifile, ofile):
    "Öffnet die CSV Datei, überführt sie in das neue Format und exportiert sie."

    print('[i] Lese aus ' + ifile.name + ' und schreibe in ' +
          ofile.name)
    with open(
            ifile, mode='r') as infile, open(
                ofile, mode='w') as outfile:
        reader = csv.DictReader(
            infile,
            fieldnames=[
                'Post Nummer', 'Sendungsnummer', 'Referenz1', 'Referenz2',
                'Gewicht', 'Empf.Name1', 'Empf.Adresse', 'Empf.PLZ',
                'Empf.Ort', 'Kostenstelle', 'Produkt'
            ],
            delimiter=';')
        fn = [
            'Post Nummer', 'Referenz1', 'Referenz2', 'Sendungsnummer',
            'Gewicht', 'Empf.Name1', 'Empf.Adresse', 'Empf.PLZ', 'Empf.Ort',
            'Kostenstelle', 'Produkt'
        ]
        writer = csv.DictWriter(
            outfile, extrasaction='ignore', fieldnames=fn, delimiter=';')
        # reorder the header first
        try:
            for row in reader:
                # writes the reordered rows to the new file
                writer.writerow(row)
        except Exception as e:
            print('[!] Fehler bei der Bearbeitung der CSV Datei:')
            print('[!] ' + str(e))
            print(
                '[!] Bitte ueberpruefen, ob es sich um eine korrekte CSV Datei handelt!'
            )
            sys.exit(1)


def checkInputFromUser(path):
    "Überprüfe ob das Verzeichnis existiert."

    if not path.exists():
        print(
            '[!] Die Eingabe ist kein Verzeichnis. Bitte ein gueltiges Verzeichnis eingeben.'
        )
        sys.exit(1)

    return True


def findCSVFile(path):
    "Finde alle CSV Dateien im Verzeichnis path."

    all_files = []
    all_files.extend(Path(path).glob('*.csv'))
    if len(all_files) == 0:
        # print('[!] Keine CSV Dateien gefunden. Bitte Pfad überprüfen.')
        # sys.exit(1)
        return None
    elif len(all_files) > 1:
        print('[i] Mehrere CSV Dateien gefunden. Nehme ersten Fund:')
        return all_files[0]


def moveInputFile(input):
    "Verschiebe Input Datei in Unterordner und füge Suffix hinzu."

    movepath = Path(input.parent / 'processed')
    targetname = input.with_suffix(input.suffix + '.success')
    fulltarget = movepath / targetname.name
    input.replace(fulltarget)


class CSVConvertSvc(win32serviceutil.ServiceFramework):
    # you can NET START/STOP the service by the following name
    _svc_name_ = "blub"
    # this text shows up as the service name in the Service
    # Control Manager (SCM)
    _svc_display_name_ = "bar der AT CSV Dateien."
    # this text shows up as the description in the SCM
    _svc_description_ = "Dieser Dienst öffnet die AT CSV Datei und überführt sie in das DPD Format."

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        # create an event to listen for stop requests on
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    # core logic of the service
    def SvcDoRun(self):
        import servicemanager

        rc = None
        inputpath = Path(r'C:\Users\Dennis\Documents')
        outputpath = Path(r'C:\Users\Dennis\Desktop')
        file = None

        # if the stop event hasn't been fired keep looping
        while rc != win32event.WAIT_OBJECT_0:

            checkInputFromUser(inputpath)

            while file is None:
                file = findCSVFile(inputpath)
                if file is None:
                    time.sleep(60)

            inputfile = file
            outputfile = outputpath / 'out.csv'
            reorder_AT_csv(inputfile, outputfile)
            moveInputFile(inputfile)

            # block for 5 seconds and listen for a stop event
            rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)

    # called when we're being shut down
    def SvcStop(self):
        # tell the SCM we're shutting down
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        # fire the stop event
        win32event.SetEvent(self.hWaitStop)


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(CSVConvertSvc)

这个版本没有做它应该做的事情。然而,我一开始可以把它作为一个非服务版本,而是一个简单的 python 脚本,它可以完成它应该做的事情:

#!/usr/bin/env python3

import sys
import os
import csv
import time
from pathlib import Path




def reorder_AT_csv(ifile, ofile):
    "Öffnet die CSV Datei, überführt sie in das neue Format und exportiert sie."

    print('[i] Lese aus ' + ifile.name + ' und schreibe in ' +
          ofile.name)
    with open(
            ifile, mode='r') as infile, open(
                ofile, mode='w') as outfile:
        reader = csv.DictReader(
            infile,
            fieldnames=[
                'Post Nummer', 'Sendungsnummer', 'Referenz1', 'Referenz2',
                'Gewicht', 'Empf.Name1', 'Empf.Adresse', 'Empf.PLZ',
                'Empf.Ort', 'Kostenstelle', 'Produkt'
            ],
            delimiter=';')
        fn = [
            'Post Nummer', 'Referenz1', 'Referenz2', 'Sendungsnummer',
            'Gewicht', 'Empf.Name1', 'Empf.Adresse', 'Empf.PLZ', 'Empf.Ort',
            'Kostenstelle', 'Produkt'
        ]
        writer = csv.DictWriter(
            outfile, extrasaction='ignore', fieldnames=fn, delimiter=';')
        # reorder the header first
        try:
            for row in reader:
                # writes the reordered rows to the new file
                writer.writerow(row)
        except Exception as e:
            print('[!] Fehler bei der Bearbeitung der CSV Datei:')
            print('[!] ' + str(e))
            print(
                '[!] Bitte ueberpruefen, ob es sich um eine korrekte CSV Datei handelt!'
            )
            sys.exit(1)


def checkInputFromUser(path):
    "Überprüfe ob das Verzeichnis existiert."

    if not path.exists():
        print(
            '[!] Die Eingabe ist kein Verzeichnis. Bitte ein gueltiges Verzeichnis eingeben.'
        )
        sys.exit(1)

    return True


def findCSVFile(path):
    "Finde alle CSV Dateien im Verzeichnis path."

    all_files = []
    all_files.extend(Path(path).glob('*.csv'))
    if len(all_files) == 0:
        # print('[!] Keine CSV Dateien gefunden. Bitte Pfad überprüfen.')
        # sys.exit(1)
        return None
    elif len(all_files) > 1:
        print('[i] Mehrere CSV Dateien gefunden. Nehme ersten Fund:')
    return all_files[0]


def moveInputFile(input):

    movepath = Path(input.parent / 'processed')
    targetname = input.with_suffix(input.suffix + '.success')
    fulltarget = movepath / targetname.name
    input.replace(fulltarget)


def main():

    inputpath = Path(r'C:\Users\Dennis\Documents')
    outputpath = Path(r'C:\Users\Dennis\Desktop')
    file = None

    checkInputFromUser(inputpath)

    while file is None:
        file = findCSVFile(inputpath)
        if file is None:
            time.sleep(60)

    inputfile = file
    outputfile = outputpath / 'out.csv'
    reorder_AT_csv(inputfile, outputfile)
    moveInputFile(inputfile)


if __name__ == '__main__':
    main()

作为 Python 新手,我不知道我错过了什么。该服务已正确安装并且启动也没有问题。我使用的是 ActiveState Python 3.6,它随 pywin32 库一起提供。

最佳答案

使用logging报告计划进展 and do debug printing 。这样,您将看到程序正在做什么以及卡在哪里。

(另请注意 ServiceFramework 具有“ Debug模式”。从控制台运行 <your_program> debug 会指示 HandleCommandLine 以交互方式运行程序:您将获得控制台输出,并且 Ctrl-C 将终止程序。这使得运行修复迭代花费更少的时间,但不会揭示仅在作为服务运行时出现的错误。因此它很有帮助,但只是初步步骤,作为服务运行并记录到文件是最终的测试。 )

<小时/>

以下是我如何安排无人值守/作为服务运行的脚本。

  • 尽快设置日志记录。
    始终使用旋转处理程序,以便日志不会无限期增长。
    确保记录所有未处理的异常。

    # set up logging #####################################
    import sys,logging,logging.handlers,os.path
    #in this particular case, argv[0] is likely pythonservice.exe deep in python's lib\
    # so it makes no sense to write log there
    log_file=os.path.splitext(__file__)[0]+".log"
    l = logging.getLogger()
    l.setLevel(logging.INFO)
    f = logging.Formatter('%(asctime)s %(process)d:%(thread)d %(name)s %(levelname)-8s %(message)s')
    h=logging.StreamHandler(sys.stdout)
    h.setLevel(logging.NOTSET)
    h.setFormatter(f)
    l.addHandler(h)
    h=logging.handlers.RotatingFileHandler(log_file,maxBytes=1024**2,backupCount=1)
    h.setLevel(logging.NOTSET)
    h.setFormatter(f)
    l.addHandler(h)
    del h,f
    #hook to log unhandled exceptions
    def excepthook(type,value,traceback):
        logging.error("Unhandled exception occured",exc_info=(type,value,traceback))
        #Don't need another copy of traceback on stderr
        if old_excepthook!=sys.__excepthook__:
            old_excepthook(type,value,traceback)
    old_excepthook = sys.excepthook
    sys.excepthook = excepthook
    del log_file,os
    # ####################################################
    
  • 记录每个程序的启动和停止。
    对于服务,还必须在SvcDoRun处手动记录未处理的异常。自pythonservice.exe以来的水平似乎吞噬了所有异常(exception)。保留sys.excepthook无论如何都要更换,以防万一。

    def SvcDoRun(self):
        #sys.excepthook doesn't seem to work in this routine -
        # apparently, everything is handled by the ServiceFramework machinery
        try:
            l.info("Starting service")
            main()
        except Exception,e:
            excepthook(*sys.exc_info())
        else:
            l.info("Finished successfully")
    def SvcStop(self):
        l.info("Stop request received")
        <...>
    
  • 以用户的术语记录程序执行的任何有意义的步骤。以更详细的方式报告琐碎或非常频繁的事件。以输出任意 l.setLevel() 的方式选择级别。给出了完整的图片,以及相应的详细程度。

    file_ = findCSVFile(inputpath)
    if file_:
        l.info("Processing `%s'", file_)    # Note the quotes around the name.
                                            # They will help detect any leading/trailing
                                            #space in the path.
    else:
        l.debug("No more files")
    
    <...>
    
    l.info("Moving to `%s'",fulltarget)
    input.replace(fulltarget)
    
    <...>
    
    l.debug("waiting")
    rc = win32event.WaitForSingleObject(<...>)
    

关于python - 如何调试作为服务运行的Python程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51194784/

相关文章:

python - 使用python在单个pdf页面上保存多个绘图

python - 如何将 Heroku 上的不同包要求到本地盒子?

python - pyttsx3 模块未显示所有已安装的声音

Python win32 : error

python - 使用 pywin32(win32evtlog 模块)在 Python 中读取 Windows 事件日志

用于在二叉树中查找最大路径的Python算法无法按预期工作

python - 从多个模型创建模型以添加到数据库?

c# - 如何在 Windows 10 通用应用程序中使用 isTypePresent 检测相机是否可用

适用于Windows 10的Docker//./pipe/docker_engine : access is denied

python - 多个 WindowsBaloonTip/TrayTip 通知?