Python脚本停止编写,但显示为正在运行的进程

Python脚本停止编写,但显示为正在运行的进程,python,performance,shared-libraries,Python,Performance,Shared Libraries,我正在linux服务器上的屏幕上运行python脚本,当我执行TOP命令时,我可以看到它正在运行,但几个小时以来,该脚本一直没有编写任何内容。有人知道原因是什么吗 这是我的剧本: import GeoIP from netaddr import * gi = GeoIP.GeoIP("/data/GeoIPOrg_20141202.dat", GeoIP.GEOIP_MEMORY_CACHE) o = Path to the output text file for line in f:

我正在linux服务器上的屏幕上运行python脚本,当我执行TOP命令时,我可以看到它正在运行,但几个小时以来,该脚本一直没有编写任何内容。有人知道原因是什么吗

这是我的剧本:

import GeoIP
from netaddr import *

gi = GeoIP.GeoIP("/data/GeoIPOrg_20141202.dat", GeoIP.GEOIP_MEMORY_CACHE)
o = Path to the output text file

for line in f:
    line = line.strip('\n')
    asn,ip,count =line.split('|')
    org = gi.org_by_addr(ip)
    start,end = gi.range_by_ip(ip)
    ran = list(IPRange(start,end))
#    ipcount = len(ran)
    ip_start,ip_end = IPAddress(start),IPAddress(end)
    n_start = int(ip_start)
    n_end = int(ip_end)
    range = (n_start,n_end)
    print ("%s|%s|%s|%s|%s|%s" % (asn,range,len(ran),org,ip,count) , file = o)

这可能是一些事情;如果看不到您是如何运行以及如何初始化该文件,很难说

一个明确的可能性是文件没有被调用(更相关的是,请参阅关于更改缓冲区大小的文档,因为它可能在代码中被调用)

无论哪种方式,都值得使用Python(2.5+)的
with
语句来灵活、稳健地处理文件/资源管理,而不是依赖
打印,例如:

with open("/my/output/path.txt", "w") as out_file:
    # Rest of code
    # ...
    out_file.write("%s|%s|%s|%s|%s|%s\n" % (asn,range,len(ran),org,ip,count))

有关将
语句一起使用的示例,请参阅。

实现此目的有两种方法

  • 您可以将代码更改为使用
    with
    语句(上下文) 经理)正如@Nick B在其回答中建议的那样,打开您的文件 在那里
  • 或者,您可以在打开文件的位置设置缓冲区 行缓冲
  • 所以你说:

    # Im assuming you open your file like this since your code is
    # an incomplete snippet. Otherwise tell us how you open your file
    o = open('output_file.log', 'w')  
    
    你必须说:

    o = open('output_file.log', 'w', buffering=1)  # enable line buffering
    

    您应该通过在交互式python shell中键入
    help(open)
    来阅读
    open
    命令的帮助。它在很大程度上解释了python中缓冲的工作原理。

    在打印的
    file=o
    部分中使用的
    o
    是什么?in是输出文件。不重要您知道它没有写任何东西吗?@Nick B因为文件最后打印行的大小+内容保持不变
    打开(“/my/output/path.txt”)作为out\u文件:
    应该是
    打开(“/my/output/path.txt”,“w”)作为out\u文件:
    此解决方案将删除单独的行。我该怎么处理呢?@Mee-good point-需要一个新行来保持它与您的版本相同,所以我相应地更新了答案