我对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
答案 0 :(得分:2)
Windows服务要记住的一件事是,默认情况下,它们在LOCAL_SYSTEM帐户下运行。这意味着应用本地卷的权限(当然可以拒绝LOCAL_SYSTEM访问任何给定的文件夹),并且LOCAL_SYSTEM无权访问任何网络卷。
答案 1 :(得分:1)
我不熟悉pywin32的ServiceFramework
,但根据您的代码和错误消息,我打赌您在path_to_watch
时遇到问题。
我假设您已清理了示例的文件夹名称,而您实际上并未查找folder
。
怎么样:
尝试使用:
path_to_watch = r"c:\foo\bar" + "\\"