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

时间:2018-07-05 15:12:39

标签: 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来说是非常陌生的人,我无法弄清楚自己缺少什么。该服务已正确安装,并且也可以正常启动。我正在使用pywin32库附带的ActiveState Python 3.6。

2 个答案:

答案 0 :(得分:0)

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

(还要注意,ServiceFramework具有“调试模式”。从控制台运行<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似乎吞没了所有异常。始终保留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(<...>)
    

答案 1 :(得分:0)

一个问题是

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

有自己的异常处理程序。因此,即使您将 std out 和 err 重定向到文件,您也不会看到在那里打印未处理的异常。 但是有一个解决方案:

# core logic of the service
def SvcDoRun(self):
    try:
        self.server = MyLauncher()
        self.server.run()
    except:
        import traceback
        print(traceback.format_exc())

另一个答案中提到的改变的excepthook在我的情况下不起作用: