原理:利用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)
CopyDvd2Hard.py
__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()