当Windows服务读取配置文件时,如何编写代码以避免错误?

时间:2015-09-09 11:38:29

标签: python windows service config

我有文件树:

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来处理服务,但错误。

如果我将目录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,我该怎么办? 谢谢!

1 个答案:

答案 0 :(得分:1)

如果您使用文件或目录名称的相对路径,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'])