某软件上报数据的机制是重启客户端PC会上报一次数据,而干掉然后重启进程并不算是一次重启,其实是在重启时,读取config.ini文件的lastShutDownTime,修改lastShutDownTime的值后,重启进程会记录为重启一次且上报数据
最近在看python,计划使用python写一个脚本实现该目的
建立一个restartRs.py的工程,首先是读写配置文件的操作
由于只需要修改该文件的第21和22行,故读取整个.ini文件后,修改制定行的值,然后写入文件即可
r=open('C:/Program Files (x86)/xxx/xxxx/config.ini','r+')
flist=r.readlines()
flist[20]='lastShutDownTime =Thfffffu Nov 0df3 09:06:21 2erd016\n'
flist[21]='1cacheDevUsers = 100\n'
w=open('C:/Program Files (x86)/xxx/xxxx/config.ini','w+')
w.writelines(flist)
验证发现读写是成功的
好,继续下一步,关闭进程后启动进程
skill = os.system('taskkill /F /IM abcd.exe')
time.sleep(1)
start = Popen([r'C:\Program Files (x86)\xxx\xxxx\abcd.exe'])
OK,可正常关闭和启动进程
执行代码,结束后可成功实现业务逻辑
因为是压测产生数据,故需要循环执行,
import os
import time
from subprocess import Popen
for num in range(1,3):
r=open('C:/Program Files (x86)/xxx/xxxx/config.ini','r+')
flist=r.readlines()
flist[20]='lastShutDownTime =Thfffffu Nov 0df3 09:06:21 2erd016\n'
flist[21]='1cacheDevUsers = 100\n'
w=open('C:/Program Files (x86)/xxx/xxxx/config.ini','w+')
w.writelines(flist)
skill = os.system('taskkill /F /IM abcd.exe')
time.sleep(1)
start = Popen([r'C:\Program Files (x86)\xxx\xxxx\abcd.exe'])
print 'it is the '+str(num) + ' times'
循环的第二次时,报错
Traceback (most recent call last):
File "C:/Users/llz/PycharmProjects/HelloWord/restartRs.py", line 16, in <module>
flist[20]='lastShutDownTime =Thfffffu Nov 0df3 09:06:21 2erd016\n'
IndexError: list assignment index out of range
开始怀疑是因为业务间并没有等待会引起时间差导致错误,修改后发现并不是。逐个排查仍未找出原因,仔细一看,文件读写后并没有close,这样会引起下次读写出错。在读写后加上.close()函数即可
r=open('C:/Program Files (x86)/xxx/xxxx/config.ini','r+')
flist=r.readlines()
r.close()
flist[20]='lastShutDownTime =Thfffffu Nov 0df3 09:06:21 2erd016\n'
flist[21]='1cacheDevUsers = 100\n'
w=open('C:/Program Files (x86)/xxx/xxxx/config.ini','w+')
w.writelines(flist)
w.close()
OK,循环执行,但是发现数据并没有上报,而是执行结束后,等待一小会才会上报数据。什么问题导致的呢,原来每次重启后,客户端需要连接请求服务器成功后才会上报数据。因为等待时间过短,在进程起来后,并没有成功初始化网络连接服务端就开始关闭启动进程,这样导致数据一直写在本地没有上报
修改在进程起来后,等待5秒钟,再次修改配置文件,即可成功实现业务
完整代码如下:
__author__ = 'llz'
import os
import time
from subprocess import Popen
conf = 'C:/Program Files (x86)/xxx/xxxx/config.ini'
serviceEXE = r'C:\Program Files (x86)\xxx\xxxx\abcd.exe'
for num in range(1,3):
r=open(conf,'r+')
flist=r.readlines()
r.close()
print "read the file"
flist[20]='lastShutDownTime =Thfffffu Nov 0df3 09:06:21 2erd016\n'
print flist[20]
flist[21]='1cacheDevUsers = 100\n'
w=open(conf,'w+')
w.writelines(flist)
w.close()
print "write the file"
time.sleep(1)
skill = os.system('taskkill /F /IM abcd.exe')
print "kill abcd.exe"
time.sleep(1)
sstart = Popen([serviceEXE])
print "start abcd.exe"
print "waitwait 1 seconds"
time.sleep(5)
print 'it is the '+str(num) + ' times'