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 来操作服务,但是错误。

如果我将目录 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'

或(python2.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'])