【发布时间】:2018-04-17 20:30:30
【问题描述】:
我的代码有点小问题。
首先是代码:
import os
import subprocess
import httplib, urllib
for ip in range(1,255):
ip_addr = "192.168.1." + str(ip)
res = subprocess.call(["ping", ip_addr, "-c1", "-W1", "-q"], stdout=open(os.devnull,'w'))
if res == 0:
print (ip_addr) + " reachable"
else:
print (ip_addr) + " not reachable"
f = open('state_All.txt','r')
prestate = f.readline(ip)
f.close()
prestate = ord(prestate)
res = res + 97
if not prestate == res:
if prestate == 97:
conn = httplib.HTTPSConnection("api.pushover.net:443")
## The Code in here which I have deleted out is definitely not the problem,
## works 100% safe and can't be share beacuse of security problems.
}), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse()
else:
conn = httplib.HTTPSConnection("api.pushover.net:443")
## The Code in here which I have deleted out is definitely not the problem,
## works 100% safe and can't be share beacuse of security problems.
}), { "Content-type": "application/x-www-form-urlencoded" })
conn.getresponse()
f = open('state_All.txt','w')
res = str(unichr(res))
data = (res[ip])
f.writelines(data)
f.close()
问题:
读取 .txt 中的某些特定行有效,但我无法在特定行上写入之后的测量状态,
我收到了这个错误:
Traceback (most recent call last):
File "ping_All.py", line 48, in <module>
data = (res[ip])
IndexError: string index out of range
希望有人可以帮助我。
【问题讨论】:
-
看起来
res的字符串长度不超过 255 个字符...为什么使用ip作为字符串索引?第 48 行引发错误的操作是尝试访问字符串中的字符,但您的字符串不够长。
标签: python text-files