Python写入文件
问题描述:
我在运行在debian服务器上的小型python脚本中遇到了一些问题。Python写入文件
首先它应该做的:
- 从服务器列表 - >工作
- 转换为真正的字符串列表 - >工作
- 写入文件 - >不做任何事...
已经尝试在python接口(>>>)中使用相同的代码,并且它按照它应该的方式写入所有内容。
文件已经被创建并且获得了一个chmod 777。
即使检查如果没有accidentially那素文字的另一实例正在运行的锁定文件,但没有...
任何人有一个想法,为什么开始,但在接口时,它不会写文件?
而现在这里的脚本本身:
#!/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分钟
答
来连接字符串,使用+
操作。 &
是bitwise AND - 两个字符串调用它会导致TypeError
:
>>> "[" & ""
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: unsupported operand type(s) for &: 'str' and 'str'
你的毯子except
抑制了这个错误。与
with open("/var/log/torblocker.log", "a") as torf:
torf.write("[" + time.strftime("%a, %d %b %Y %H:%M") + "] " +
"Sucessfully updated tor blacklist")
更换
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
如果你想忽略时,文件无法写入例外,围绕与try .. except IOError:
。
答
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")))
请不要使用裸体'除了:'子句。他们很可能隐藏了你得到的例外。 – bernie 2013-02-12 18:23:54
的确 - 我知道'except'子句应该设置为写入日志文件,但是尝试注释掉所有'except'子句并只看看会发生什么 – 2013-02-12 18:25:00