我有一个python脚本,在控制台中运行时运行良好。但是,当使用pywin32
使其作为服务运行时,服务将安装并正常启动,但不会产生所需的输出。因此,一定是出了什么问题--但我看不出发生了什么,无法找出原因。
该脚本执行以下操作:
让我先向您展示作为服务实现的版本的代码:
#!/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 Python3.6。
发布于 2021-07-14 19:53:17
一个问题是
# core logic of the service
def SvcDoRun(self):
具有自己的异常处理程序。因此,即使您将std重定向到一个文件并出错,您也不会在那里看到打印出一个未处理的异常。但是有一个解决方案:
# core logic of the service
def SvcDoRun(self):
try:
self.server = MyLauncher()
self.server.run()
except:
import traceback
print(traceback.format_exc())
在另一个答案中提到的更改的excepthook在我的情况下不起作用:
https://stackoverflow.com/questions/51194784
复制相似问题