簡體   English   中英

Windows服務讀取配置文件時,如何編寫代碼以避免錯誤?

[英]How do I write code to avoid error when windows service read config file?

我有文件樹:

f:/src/
   restore.ini
   config.py
   log.py
   service.py
   test.py

test.py代碼如下:

import service
import log
import config

class Test(object):
    def __init__(self):
        super(Test, self).__init__()

    def setUp(self):
        self.currentRound = int(config.read_config_co(r'restore.ini', 'Record')['currentRound'])

    def testAction(self):
        log.info(self.currentRound)

    def tearDown(self):
        config.write_config_update_co(self.currentRound-1, 'Record', 'currentRound', r'restore.ini')


class PerfServiceThread(service.NTServiceThread):

    def run (self):
        while self.notifyEvent.isSet():
            try:
                test = Test()
                test.setUp()
                test.testAction()
                test.tearDown()
            except:
                import traceback
                log.info(traceback.format_exc())


class PerfService(pywinservice.NTService):
    _svc_name_ = 'myservice'
    _svc_display_name_ = "My Service"
    _svc_description_ = "This is what My Service does"
    _svc_thread_class = PerfServiceThread


if __name__ == '__main__':
    pywinservice.handleCommandLine(PerfService)

現在,我使用cmdline python test.py installpython test.py start to action服務,但是出錯。

如果我將目錄src所有文件移動到C:\\Python27\\Lib\\site-packages\\win32\\src ,然后更改代碼:

self.currentRound = int(config.read_config_co(r'src\restore.ini', 'Record')['currentRound'])

config.write_config_update_co(self.currentRound-1, 'Record', 'currentRound', r'src\restore.ini')

現在好啦!

我不想移動目錄src ,該怎么辦? 謝謝!

如果您使用相對路徑作為文件名或目錄名,則python會在當前工作目錄(bash中的$ PWD變量;在Windows上類似)中查找(或創建)它們。

如果您想讓它們相對於當前的python文件,可以使用(python 3.4)

from pathlib import Path
HERE = Path(__file__).parent.resolve()
RESTORE_INI = HERE / 'restore.ini'

或(python 2.7)

import os.path
HERE = os.path.abspath(os.path.dirname(__file__))
RESTORE_INI = os.path.join(HERE, 'restore.ini')

如果您的restore.ini文件與python腳本位於同一目錄中。

那你可以用在

def setUp(self):
    self.currentRound = int(config.read_config_co(RESTORE_INI, 
                           'Record')['currentRound'])

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM