Python写入文件

标签 python python-3.x debian urllib2

我在 debian 服务器上运行的小 python 脚本中遇到了一个小问题。

首先它应该做什么:
- 从服务器获取列表 -> 工作
- 转换为真正的字符串列表 -> 工作
- 写入文件 -> 什么都不做...

已经尝试在 python 界面中使用相同的代码 (>>>),它按照应有的方式编写了所有内容。
文件已创建并在其上设置了 chmod 777。
即使不是意外地检查了该 scipt 的另一个实例正在运行,它锁定了文件但什么都没有......

有人知道为什么它不会在启动时写入文件,而是在界面中写入文件吗?

现在这是脚本本身:

#!/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 抑制了那个错误。替换

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: 将其包围。

关于Python写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14839111/

相关文章:

java - Google App Engine Go-Python/Java 混合应用

python - 尝试将对象转换为 DateTime,出现 TypeError

python - 复数的 `j` 后缀如何工作?我可以创建自己的后缀吗?

linux - Debian:SSH 并运行一个进程,如果 SSH 连接关闭,该进程不会终止

linux - apt-get更新debian错误

python - Keras 中一维 CNN 的激活函数错误

python - 保护 Typeform Webhook Python

python - python中的矩阵文件到字典

python - 使用 xlwings 排序 (pywin32)

iis - 将 ASP.NET 5 MVC 6 应用程序部署到 Linux 和 IIS 7