简体   繁体   English

将进度(百分比)输出到python中的文件

[英]Output progress (percentage) to a file in python

I need a way to estimate how long my program will take to complete. 我需要一种方法来估算我的程序将花费多长时间。 It is currently spending most its time in a nested for loop. 目前,它大部分时间都在嵌套的for循环中使用。 I wish to see how many iterations have occured inside this for loop to get an idea of how long it will take to get a processed output file. 我希望看到在此for循环中发生了多少次迭代,以了解获得处理后的输出文件将花费多长时间。 Is there a way to output the % done to a file in python? 有没有办法将完成的%输出到python中的文件?

Here is my current approach, but when I try to read the progress file, it is always empty. 这是我当前的方法,但是当我尝试读取进度文件时,它始终为空。 I thought by closing the file, I would be able to see what has been written. 我以为通过关闭文件,我将能够看到所写的内容。

 48     #Estimate finishing time
 49     progTotal = len(f1)
 50     prog = 0
 51
 52     #Now to calculate 1st order Walsh Coefficients by subtracting away 2nd order coefficients
 53     for g in f1:
 54         progFile = open("progress",'w')
 55         sumOfOtherWalsh = 0
 56         for gPair in w2:
 57             if g == gPair[0] or g == gPair[1]:
 58                 sumOfOtherWalsh += w2.get(gPair, 0) #Add the walsh value into sum, if it is there
 59         f1[g] -= sumOfOtherWalsh #subtract all the Walsh values as well as the value in f1
 60         progFile.write(str(float(prog)/progTotal)+"\n")
 61         prog += 1
 62         progFile.close()

Surprisingly couldn't find information on this here, so I assume I am doing it wrong, but thanks for the help anyways. 令人惊讶的是,在这里找不到有关此信息,因此我认为我做错了,但是无论如何还是要感谢您的帮助。

As for displaying the progress of your computations to stdout you could use the progressbar module. 至于显示计算到标准输出的进度,您可以使用progressbar模块。

Example: 例:

import time
import progressbar

maxval = 100
pbar = progressbar.ProgressBar(maxval=maxval)
pbar.start()
for i in range(maxval):
    # do something
    time.sleep(0.05)
    pbar.update(i+1)
pbar.finish()

Output: 输出:

$ python test.py
52% |#####################################                                    |

As for getting the output to file, it is not required that you close the file to get to see the output, but to flush the output buffers. 至于将输出保存到文件中,不需要关闭文件即可查看输出,而是刷新输出缓冲区。 (In fact it will be inefficient and probably counterproductive to open and possibly truncate the file repeatedly in the body of your loop.) (实际上,在循环体内重复打开和截断文件可能会效率低下,并且可能适得其反。)

Have a look at the file object's flush and the os module's fsync methods for flushing the file content to disk. 看一下文件对象的刷新os模块将文件内容刷新到磁盘的fsync方法。 However, this should usually not be required. 但是,通常不需要这样做。 When you write enough data to the file, the buffers will be flushed as fast as you can print it to the terminal. 当您将足够的数据写入文件时,缓冲区将尽快刷新,您可以将其打印到终端上。 (So that you can usually tail -f progess_file the output without a problem.) (这样,您通常可以在输出时tail -f progess_file没有问题。)

If it's logging what you want to achieve, have a look at the logging module . 如果要记录您要实现的目标,请查看logging模块 You can use it to get a nice extendable logging system. 您可以使用它来获得一个不错的可扩展日志记录系统。 You can select whether or not to do the logging to file or to stdout at a single point in the code. 您可以选择在代码中的一点上记录到文件还是标准输出。 You can attach other modules' logging activities to the same log by just "getting" the main logger there by name: 您可以通过按名称“获取”主记录器来将其他模块的记录活动附加到同一日志:

logger = logging.getLogger("__main__")

(Alternatively, you can very well set up another logger using a different name there.) (或者,您可以在那里使用其他名称很好地设置另一个记录器。)

Example: 例:

import time
import logging

# set up the logging
def setup_logger(logfilename = None):
    logger = logging.getLogger(__name__) # probably __name__ == "__main__" 
    logger.setLevel(logging.DEBUG)
    formatter = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s')
    if logfilename:
        # write to logfile
        handler = logging.FileHandler(logfilename)
    else:
        # write to stdout
        handler = logging.StreamHandler()
    handler.setFormatter(formatter)
    logger.addHandler(handler)
    return logger
logger = setup_logger("test.log")

# example use of the logger
maxval = 100
for i in range(1,maxval+1):
    # do something
    time.sleep(0.05)
    if (i)%(maxval/10) == 0:
        logger.debug("progress:% 4d %% done", i)

Output: 输出:

2013-05-15 21:03:23,313 - DEBUG - progress:  10 % done
2013-05-15 21:03:23,822 - DEBUG - progress:  20 % done
2013-05-15 21:03:24,323 - DEBUG - progress:  30 % done
2013-05-15 21:03:24,825 - DEBUG - progress:  40 % done
2013-05-15 21:03:25,326 - DEBUG - progress:  50 % done
2013-05-15 21:03:25,827 - DEBUG - progress:  60 % done
2013-05-15 21:03:26,328 - DEBUG - progress:  70 % done
2013-05-15 21:03:26,829 - DEBUG - progress:  80 % done
2013-05-15 21:03:27,330 - DEBUG - progress:  90 % done
2013-05-15 21:03:27,831 - DEBUG - progress: 100 % done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM