为什么在Windows中运行Python脚本作为服务不能将数据写入文本?

2024-03-28 10:59:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我想复制与Windows Services in Python相同的结果:

import win32service  
import win32serviceutil  
import win32event  

class PySvc(win32serviceutil.ServiceFramework):  
    # you can NET START/STOP the service by the following name  
    _svc_name_ = "PySvc"  
    # this text shows up as the service name in the Service  
    # Control Manager (SCM)  
    _svc_display_name_ = "Python Test Service"  
    # this text shows up as the description in the SCM  
    _svc_description_ = "This service writes stuff to a file"  

    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  
        print 'hello'

        f = open('test.dat', 'w+')  
        rc = None  

        # if the stop event hasn't been fired keep looping  
        while rc != win32event.WAIT_OBJECT_0:  
            f.write('TEST DATA\n')  
            f.flush()  
            # block for 5 seconds and listen for a stop event  
            rc = win32event.WaitForSingleObject(self.hWaitStop, 5000)  

        f.write('SHUTTING DOWN\n')  
        f.close()  

    # 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(PySvc)  

cmd管理员模式下,我键入这些命令,它就可以工作了很好。而且告诉我Python Test Service开始。在

python.exe .\PySvc.py install

NET START PySvc

但是文件test.dat不是创造了。所以如何使程序成为SvcDoRun函数?在


Tags: thenameinimportselfeventserviceutil
1条回答
网友
1楼 · 发布于 2024-03-28 10:59:25

正在将注释转换为答案。。。在

尝试使用完整路径测试数据文件(C:\servicedata\test,dat)。在interperter中运行的路径与作为服务运行时的路径不同。在

相关问题 更多 >