Служба Windows Python не может генерировать / записывать в CSV - PullRequest
0 голосов
/ 12 января 2019

Я делаю службу Windows, написанную на Python 3.6.6. Когда я устанавливаю его в services.msc, он останавливается, когда генерирует csv-файл с моего сервера: MySQL Work Bench CE. Когда я отлаживаю свою службу Windows, это ошибка.

Ошибка:

Debugging service MyWindowsService - press Ctrl+C to stop.
Info 0x40001002 - The MyWindowsService service has started.
Error 0xC0000003 - The instance's SvcRun() method failed

<Error getting traceback - traceback.print_exception() failed

(null): (null)

Это код MyWindowService.

import time
import random
import datetime
from pathlib import Path
from SMWinservice.SMWinservice import SMWinservice
import mysql.connector as db
from mysql.connector import errorcode
from UnicodeSupportForCsv import UnicodeWriter
import csv
import sys
import os
import subprocess
from masterdata import gen_master_data


class MyWinserv(SMWinservice):

    _svc_name_ = "MyWindowsService"
    _svc_display_name_ = "My Windows Service"
    _svc_description_ = "My Windows Service"

    def start(self):
        self.isrunning = True

    def stop(self):
        self.isrunning = False

    def main(self):
        i = 0
        while self.isrunning:
            now = datetime.datetime.now()
            a = now.replace(hour=10, minute=25)
            b = now.replace(hour=16, minute=58)
            if(now==a):
                    gen_master_data.tablename_brand()
                    time.sleep(5)
            if(now==b):
                    random.seed()
                    x = random.randint(1, 1000000)
                    Path(f'c:\\{x}.txt').touch()
                    time.sleep(5)

if __name__ == '__main__':
    MyWinserv.parse_command_line()

Это SMWinService:

import socket

import win32serviceutil

import servicemanager
import win32event
import win32service


class SMWinservice(win32serviceutil.ServiceFramework):
    '''Base class to create winservice in Python'''

    _svc_name_ = 'pythonService'
    _svc_display_name_ = 'Python Service'
    _svc_description_ = 'Python Service Description'

    @classmethod
    def parse_command_line(cls):
        '''
        ClassMethod to parse the command line
        '''
        win32serviceutil.HandleCommandLine(cls)

    def __init__(self, args):
        '''
        Constructor of the winservice
        '''
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        socket.setdefaulttimeout(60)

    def SvcStop(self):
        '''
        Called when the service is asked to stop
        '''
        self.stop()
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        '''
        Called when the service is asked to start
        '''
        self.start()
        servicemanager.LogMsg(servicemanager.EVENTLOG_INFORMATION_TYPE,
                              servicemanager.PYS_SERVICE_STARTED,
                              (self._svc_name_, ''))
        self.main()

    def start(self):
        '''
        Override to add logic before the start
        eg. running condition
        '''
        pass

    def stop(self):
        '''
        Override to add logic before the stop
        eg. invalidating running condition
        '''
        pass

    def main(self):
        '''
        Main class to be ovverridden to add logic
        '''
        pass

# entry point of the module: copy and paste into the new module
# ensuring you are calling the "parse_command_line" of the new created class
if __name__ == '__main__':
    SMWinservice.parse_command_line()

Это класс MasterData:

import mysql.connector as db
from mysql.connector import errorcode
from UnicodeSupportForCsv import UnicodeWriter
from call import configuration,query
import csv
import sys

class gen_master_data:

    #BRAND
    def tablename_brand():
        con = db.connect(**configuration.config)
        cur = con.cursor()
        cur.execute(query.brand)

        with open("d:\\test1.csv",'wb') as csvfile:
            uw = UnicodeWriter(
                csvfile, delimiter='|', quotechar='"',quoting=csv.QUOTE_NONE)
        for row in cur.fetchall():
                uw.writerow([(col) for col in row])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...