2

我已经通过 pywin32 构建了一个 Windows 服务应用程序。而且我无法在目录“%LOCALAPPDATA%”中创建任何文件或目录。我认为导致这个问题的原因可能是我的应用程序没有足够的权限来创建文件,但我不太确定。我是 Windows 编程的初学者。我怎么解决这个问题?

这是我的代码:

import traceback
import os
import sys

import win32serviceutil
import win32security
import win32api
import win32service
import win32event
import win32file

class newsLauncher(win32serviceutil.ServiceFramework):

    _svc_name_ = 'Test_service'
    _svc_display_name_ = 'Test for service'


    def __init__(self, *args):
        win32serviceutil.ServiceFramework.__init__(self, *args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)


    def log(self, msg):
        import servicemanager
        servicemanager.LogInfoMsg(str(msg))
        def sleep(self, sec):
            win32api.Sleep(sec*1000, True)


    def SvcDoRun(self):
        self.ReportServiceStatus(win32service.SERVICE_START_PENDING)
        try:
            cwd = os.path.join(os.environ['LOCALAPPDATA'], "test_service")
            os.mkdir(cwd)
            os.chdir(cwd)

            open("test.log", 'w').write("success create file.")

            self.ReportServiceStatus(win32service.SERVICE_RUNNING)

            win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)
            self.ReportServiceStatus(win32service.SERVICE_STOPPED)
        except Exception as e:
            self.log('Exception: %s' % e)
            self.log('line %d' % traceback.tb_lineno(sys.exc_info()[2]))
            self.SvcStop()
            self.ReportServiceStatus(win32service.SERVICE_STOPPED)


    def SvcStop(self):
        self.log("in stop")

        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)

        win32event.SetEvent(self.hWaitStop)
        self.log("stoped")


if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(newsLauncher)
4

0 回答 0