Python語言編寫電腦時間自動同步小工具_python

來源:互聯網
上載者:User

話不多說,小工具需求如下:
功能需求 -- 電腦開機後自動執行時間同步
非功能需求 -- 安裝執行簡單,無需安裝額外環境

一、代碼實現

基於以上需求,思路如下:訪問網路擷取北京時間,然後調用命令列來設定系統時間。程式寫成Windows Service,並設定為開機自動運行。正好前段時間在學習Python,所以打算用Python來寫這個工具。具體代碼如下:

擷取網路時間

複製代碼 代碼如下:

 def getBeijinTime():
     """
    擷取北京時間
     """
     try:
         conn = httplib.HTTPConnection("www.beijing-time.org")
         conn.request("GET", "/time.asp")
         response = conn.getresponse()
         print response.status, response.reason
         if response.status == 200:
             #解析響應的訊息
             result = response.read()
             logging.debug(result)
             data = result.split("\r\n")
             year = data[1][len("nyear")+1 : len(data[1])-1]
             month = data[2][len("nmonth")+1 : len(data[2])-1]
             day = data[3][len("nday")+1 : len(data[3])-1]
             #wday = data[4][len("nwday")+1 : len(data[4])-1]
             hrs = data[5][len("nhrs")+1 : len(data[5])-1]
             minute = data[6][len("nmin")+1 : len(data[6])-1]
             sec = data[7][len("nsec")+1 : len(data[7])-1]

             beijinTimeStr = "%s/%s/%s %s:%s:%s" % (year, month, day, hrs, minute, sec)
             beijinTime = time.strptime(beijinTimeStr, "%Y/%m/%d %X")
             return beijinTime
     except:
         logging.exception("getBeijinTime except")
         return None

同步本地系統時間
複製代碼 代碼如下:

 def syncLocalTime():
     """
     同步本地時間
     """
     logging.info("current local time is: %d-%d-%d %d:%d:%d" % time.localtime()[:6])

     beijinTime = getBeijinTime()
     if beijinTime is None:
         logging.info("get beijinTime is None, will try again in 30 seconds...")
         timer = threading.Timer(30.0, syncLocalTime)
         timer.start();
     else:
         logging.info("get beijinTime is: %d-%d-%d %d:%d:%d" % beijinTime[:6])

         tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec = beijinTime[:6]
         import os
         os.system("date %d-%d-%d" % (tm_year, tm_mon, tm_mday))     #設定日期
         os.system("time %d:%d:%d.0" % (tm_hour, tm_min, tm_sec))    #設定時間
         logging.info("syncLocalTime complete, current local time: %d-%d-%d %d:%d:%d \n" % time.localtime()[:6])

二、部署安裝

為了讓Python程式能以Windows服務的方式運行,需要用到py2exe(用來把Python程式編譯成exe)和Python Win32 Extensions 。(py2exe把Python代碼編譯成Winodws服務時依賴此組件)下載並安裝這兩個組件。安裝完畢後,在Python的安裝目錄下找到py2exe的Windows Service樣本({PythonRoot}\Lib\site-packages\py2exe\samples\advanced\MyService.py)。然後仿照這個樣本將上面的代碼完善一下。

Windows服務樣本

複製代碼 代碼如下:

 import win32serviceutil
 import win32service
 import win32event
 import win32evtlogutil

 class SynctimeService(win32serviceutil.ServiceFramework):
     _svc_name_ = "Synctime"
     _svc_display_name_ = "Synctime"
     _svc_description_ = "Synchronize local system time with beijin time"
    _svc_deps_ = ["EventLog"]

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)

    def SvcStop(self):
        self.ReportServiceStatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)

    def SvcDoRun(self):
        import servicemanager

        # Write a 'started' event to the event log...
        win32evtlogutil.ReportEvent(self._svc_name_,
                                    servicemanager.PYS_SERVICE_STARTED,
                                    0, # category
                                    servicemanager.EVENTLOG_INFORMATION_TYPE,
                                    (self._svc_name_, ''))

        # wait for beeing stopped...
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

        # and write a 'stopped' event to the event log.
        win32evtlogutil.ReportEvent(self._svc_name_,
                                    servicemanager.PYS_SERVICE_STOPPED,
                                    0, # category
                                    servicemanager.EVENTLOG_INFORMATION_TYPE,
                                    (self._svc_name_, ''))  

if __name__ == '__main__':
    # Note that this code will not be run in the 'frozen' exe-file!!!
    win32serviceutil.HandleCommandLine(SynctimeService) 



之後,再編寫一個steup.py檔案用來產生安裝檔案。

Setup.py

複製代碼 代碼如下:

 from distutils.core import setup
 import py2exe

 setup(
     # The first three parameters are not required, if at least a
     # 'version' is given, then a versioninfo resource is built from
     # them and added to the executables.
     version = "0.0.1",
     description = "Synchroniz local system time with beijin time",
     name = "sysctime",

     # targets to build
     # console = ["synctime.py"],
     service=["synctime"]
 )

編譯產生windows程式,如下圖:

然後在控制台中運行:setup.py py2exe ,一切順利的話會在目前的目錄下產生build和dist目錄。

控制台目錄切換到dist目錄,找到synctime.exe,在命令列中運行:

synctime.exe –install (-remove)  安裝或移除時間同步服務。

現在可以運行services.msc查看服務運行情況

可以看到服務並沒有啟動,而且啟動方式為手動。在這裡可以右擊服務選擇屬性手動把服務啟動起來,並且設定為服務自動啟動。

好吧,我承認。這樣操作跟上面的需求有點出入了,略顯麻煩。為瞭解決這個問題,自然想到的是用批處理來做。在dist目錄下分別建兩個批次檔:

installservice.bat

複製代碼 代碼如下:

 @echo off

 :: 安裝windows服務
 echo 正在安裝服務,請稍候...
 synctime.exe -install

 :: 設定服務自動啟動
 echo 正在啟動服務...
 sc config Synctime start= AUTO

:: 啟動服務
sc start Synctime

echo 服務啟動成功, 按任意鍵繼續...
pause



removeserivce.bat

複製代碼 代碼如下:

@echo off

:: 停止服務
echo 正在停止服務,請稍候...
sc stop Synctime

echo 正在卸載服務...
:: 刪除windows服務
synctime.exe -remove

echo 服務卸載完成,請按任意鍵繼續剩餘卸載...
pause

好了,現在可以把dist打個包發給老媽用了。但是,這樣發個一個壓縮包,看起來也太不專業了。解決的辦法是打一個安裝包,把bat指令碼打到安裝包裡,在安裝程式時由安裝包調用。這裡我用的是NISI(使用HM VNISEdit打包嚮導來產生打包指令碼非常方便)。

三、最終安裝效果圖

四、結尾

遺留的問題:

1、從上面的截圖可以看到,安裝程式在調用批處理時會顯示出控制台視窗。這個問題我在網上尋找資料,NSIS有相關的外掛程式可以隱藏控制台視窗調用bat檔案。
2、我原始碼中有寫記錄檔的操作,但是以Windows服務的方式運行後,記錄檔不能寫了,不知道有沒有好的解決辦法。
3、360 ...真是要人命啊....Orz..

時間同步工具及原始碼:http://www.jb51.net/softs/74865.html

編譯方法:

第一步: 安裝Python環境(什嗎?還沒有Python環境?... - -!)
第二步: 安裝相依元件
1、py2exe (目前只支援到python2.7)
2、Python Win32 Extensions

第三步(可選):安裝Nsis環境,用來編譯指令碼

第四步:將synctime.py編譯成windows程式
1、在目前的目錄下運行"setup.py py2exe",順利的話會在目前的目錄下產生dist和build目錄

第五步: 運行,有兩種運行方式:
1、將installservice.bat 和 removeservice.bat 拷貝到dist中運行即可
2(依賴第三步)、使用Nsis編譯Synctime.nsi指令碼,產生安裝包, 安裝後運行(推薦)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.