Python写入文件
我在一个运行在Debian服务器上的小Python脚本中遇到了一点问题。
首先,这个脚本应该做的事情是:
- 从服务器获取列表 -> 这个部分正常工作
- 转换成真正的字符串列表 -> 这个部分也正常工作
- 写入文件 -> 这个部分什么都没做...
我已经尝试在Python的交互界面(>>>)中使用相同的代码,结果一切都写得很好。
文件已经创建,并且设置了chmod 777的权限。
我甚至检查过是否有其他实例的脚本在运行,可能会锁住文件,但什么都没有...
有没有人知道为什么在启动时脚本不写入文件,而在交互界面中却可以?
下面是脚本的内容:
#!/usr/bin/env python
import urllib
import sys
import time
import re
exitNodes = []
readableNodes = []
class BlockTor():
def getListFromWeb(myself):
url = "https://www.dan.me.uk/torlist/"
#url = "file:///E:/test.txt"
try:
for line in urllib.request.urlopen(url):
exitNodes.append(str(line, encoding='utf8'))
for node in exitNodes:
readableNodes.append(re.sub('\\n', '', node))
#print(exitNodes)
#sys.exit()
except:
try:
f = open("/var/log/torblocker.log", "a")
#f = open("E:\\logfile.log", "a")
f.write("[" + time.strftime("%a, %d %b %Y %H:%M") + "] Error while loading new tornodes")
f.close()
except:
print("Can't write log")
pass
sys.exit()
pass
def buildList(myself):
f = open("/etc/apache2/torlist/tor-ip.conf", "w")
#f = open ("E:\\test-ips.conf", "w")
f.write('<RequireAll>\n')
f.write(' Require all granted\n')
for line in readableNodes:
f.write(' Require not ip ' + line + '\n')
f.write('</RequireAll>')
f.close()
try:
f = open("/var/log/torblocker.log", "a")
#f = open("E:\\logfile.log", "a")
f.write("[" + time.strftime("%a, %d %b %Y %H:%M") + "] Sucessfully updated tor blacklist")
f.close()
except:
pass
def torhandler(myself):
BlockTor.getListFromWeb(myself)
BlockTor.buildList(myself)
if __name__ == "__main__":
asdf = BlockTor()
BlockTor.torhandler(asdf)
编辑:
忘了提 - 如果你想测试它,请小心:这个服务器每30分钟只允许一个请求。
2 个回答
2
f.write("[" & time.strftime("%a, %d %b %Y %H:%M") & "] Error while loading new tornodes")
这是一个 TypeError
错误。要连接字符串,应该用 +
,而不是 &
。在这里,你在简单的 except
语句中捕获了这个 TypeError
。这就说明了为什么简单的 except
语句通常不是一个好主意。一般来说,只处理你预期到的,并且知道如何正确处理的错误。
你也可以使用字符串格式化的方法:
f.write('[{0}] Error while loading new tornodes'.format(time.strftime("%a, %d %b %Y %H:%M")))
9
要把字符串连接在一起,可以用 +
这个符号。&
是一个位运算符,使用它去连接两个字符串会导致一个 TypeError
错误:
>>> "[" & ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'str' and 'str'
你用的那种通用的 except
会把这个错误给压制掉。把
try:
f = open("/var/log/torblocker.log", "a")
#f = open("E:\\logfile.log", "a")
f.write("[" & time.strftime("%a, %d %b %Y %H:%M") & "] Sucessfully updated tor blacklist")
f.close() # ^ ^
except:
pass
换成
with open("/var/log/torblocker.log", "a") as torf:
torf.write("[" + time.strftime("%a, %d %b %Y %H:%M") + "] " +
"Sucessfully updated tor blacklist")
如果你想在文件无法写入时忽略这个错误,可以用 try .. except IOError:
来包裹起来。