![](/img/trans.png)
[英]How do I read / write a file in Python (3) on Windows without introducing carriage returns?
[英]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 install
和python 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.