原理:利用python的win32模块,注册服务,让代码在后台运行,检测光盘并拷贝文件
启动的方法就是直接在cmd下,main.py install ,然后去windows 的服务下就可以看到The smallestpossible Python Service 这个服务,你可以启动,停止,还可以设置成开机自动启动。启动服务后,会自动检测光盘并在后台拷贝文件
main.py
import win32serviceutil import win32service import win32event import CopyDvd2Hard class SmallestPythonService(win32serviceutil.ServiceFramework): _svc_name_ = "SmallestPythonService" _svc_display_name_ = "The smallest possible Python Service" def __init__(self, args): win32serviceutil.ServiceFramework.__init__(self, args) # Create an event which we will use to wait on. # The "service stop" request will set this event. self.hWaitStop = win32event.CreateEvent(None, 0, 0, None) def SvcStop(self): # Before we do anything, tell the SCM we are starting the stop process. self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING) # And set my event. win32event.SetEvent(self.hWaitStop) def SvcDoRun(self): #实际运行代码# CopyDvd2Hard.copydvd2hard() win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE) if __name__==‘__main__‘: win32serviceutil.HandleCommandLine(SmallestPythonService)
__author__ = ‘M‘ import os import win32file import shutil import time def copydvd2hard(dstdir=‘temp‘): #检测本地的最后一个光驱和硬盘分区 letters = [l.upper() + ‘:‘ for l in ‘abcdefghijklmnopqrstuvwxyz‘] cdrom = ‘‘ harddrive = ‘‘ for drive in letters: if win32file.GetDriveType(drive) == 3: harddrive = drive if win32file.GetDriveType(drive) == 5: cdrom = drive cdrom += ‘/‘ harddrive = harddrive + ‘/‘ + dstdir #检测光驱内是否有光盘,等待光盘插入 while os.system(‘cd /d‘ + cdrom): time.sleep(5) #拷贝文件 shutil.copytree(cdrom, harddrive) if __name__ == ‘__main__‘: copydvd2hard()
原文地址:http://blog.csdn.net/thoughts_storms/article/details/24872281