Python Win32 服务

1 投票
2 回答
3796 浏览
提问于 2025-04-15 18:17

我对Python还比较陌生,也没有写Windows服务的经验。我试着根据网上找到的一些教程拼凑了一个Windows服务。

我需要这个服务不断监控一个文件夹的变化,当它发现有变化时就运行一个脚本。以下是我目前的代码:

import win32service
import win32serviceutil
import time

class aservice(win32serviceutil.ServiceFramework):
    _svc_name_ = "aservice"
    _svc_display_name_ = "aservice - It Does nothing"

    def __init__(self,args):
        win32serviceutil.ServiceFramework.__init__(self,args)
        self.isAlive = True

    def SvcDoRun(self):
        import servicemanager
        while self.isAlive:
            # This is where i am trying to run my code...is that right?
            self.main()
            #servicemanager.LogInfoMsg("aservice - is alive and well")
            #time.sleep(5)
            #servicemanager.LogInfoMsg("aservice - Stopped")

    def SvcStop(self):
        import servicemanager
        servicemanager.LogInfoMsg("aservice - Recieved stop signal")
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        self.isAlive = False #this will make SvcDoRun() break the while loop at the next iteration.

    # This code monitors a directory for changes and calls a script when there is a change
    # At the moment, it creates a log file instead of calling the script
    def main(self):
        import os
        import win32file
        import win32con
        ACTIONS = {
            1: "Created",
            2: "Deleted",
            3: "Updated",
            4: "Renamed from something",
            5: "Ranamed to something"
        }

        FILE_LIST_DIRECTORY = 0x0001

        path_to_watch = "folder"
        hDir = win32file.CreateFile (
            path_to_watch,
            FILE_LIST_DIRECTORY,
            win32con.FILE_SHARE_READ | win32con.FILE_SHARE_WRITE,
            None,
            win32con.OPEN_EXISTING,
            win32con.FILE_FLAG_BACKUP_SEMANTICS,
            None
        )
        while 1:
            results = win32file.ReadDirectoryChangesW (
                hDir,
                1024,
                True,
                win32con.FILE_NOTIFY_CHANGE_FILE_NAME |
                win32con.FILE_NOTIFY_CHANGE_DIR_NAME |
                win32con.FILE_NOTIFY_CHANGE_ATTRIBUTES |
                win32con.FILE_NOTIFY_CHANGE_SIZE |
                win32con.FILE_NOTIFY_CHANGE_LAST_WRITE |
                win32con.FILE_NOTIFY_CHANGE_SECURITY,
                None,
                None
            )
            for action, file in results:
                #import script
                log = open ('log.txt', 'w')
                full_filename = os.path.join(path_to_watch)
                log.write(full_filename + ACTIONS.get(action, "Unknown"))
                log.close()

if __name__ == '__main__':
    win32serviceutil.HandleCommandLine(aservice)

有没有人能告诉我我哪里做错了?

补充:这是我在事件日志中看到的错误信息。

Event Type: Error
Event Source:   aservice
Event Category: None
Event ID:   3
Date:       21/01/2010
Time:       11:27:43 AM
User:       N/A
Computer:
Description:
The instance's SvcRun() method failed 
Traceback (most recent call last):
  File "C:\Python25\Lib\site-packages\win32\lib\win32serviceutil.py", line 806, in SvcRun
    self.SvcDoRun()
  File "D:\TEST\simpleservice2.py", line 35, in SvcDoRun
    self.main()
  File "D:\TEST\simpleservice2.py", line 72, in main
    None
error: (2, 'CreateFile', 'The system cannot find the file specified.') 
%2: %3

2 个回答

2

在使用Windows服务时,有一点需要注意,那就是默认情况下,它们是以LOCAL_SYSTEM账户运行的。这意味着它们对本地磁盘的权限是有效的(也就是说,LOCAL_SYSTEM账户可能会被拒绝访问某个特定的文件夹),而且LOCAL_SYSTEM账户无法访问任何网络磁盘。

1

我对pywin32的ServiceFramework不太熟悉,不过根据你的代码和错误信息,我猜你的问题可能出在path_to_watch上。

我想你在举例的时候可能把文件夹的名字处理过了,实际上你并不是在找folder

那么,你可以考虑以下几点:

  • 你是不是用了文件夹的完整路径?服务的当前工作目录可能和你想的不同。
  • 你在文件夹路径中有没有处理反斜杠?

试试用:

path_to_watch = r"c:\foo\bar" + "\\" 

撰写回答