Queue.put()方法不创建所需的输出文件(Python)

时间:2016-11-29 06:48:25

标签: python file queue output caesar-cipher

我正在使用线程和队列在python中编写一个简单的caesar密码程序。即使我的程序能够运行,它也不会创建必要的输出文件。非常感谢任何帮助,谢谢!

我猜这个异常开始于我使用队列来存储加密字符串,这里:

        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));      
        pdfDoc.addNewPage();
        Document PageOnedocument = new Document(pdfDoc,PageSize.A4);            
        addPageOneContents(PageOnedocument);  


        pdfDoc.addNewPage();
        Document PageTwodocument = new Document(pdfDoc,PageSize.A4);            
        addPageTwoContents(PageTwodocument);  

        pdfDoc.close();
        PageOnedocument.close();
        PageTwodocument.close();

以下是整个代码:

for i in range(0,len(data),l):
    while not q1.full:
        q1.put(data[index:index+l])
        index+=l
    while not q2.empty:
        output_file.write(q2.get())

1 个答案:

答案 0 :(得分:0)

while not q1.full永远不能是True,因为full是一种方法,因此在布尔上下文中始终为True,因此not q1.full将始终为False,您需要调用方法:q1.full()。与q2.full相同。

另外,在这种情况下,您应该尝试检测队列是否已满。如果它不完整,那么您将继续添加数据,然后忽略其余数据,或者index可以增加超过data的大小,并且您将继续添加0-长度数据块。

您应该使用单独的帖子写入q1并从q2阅读,然后您可以q1阻止put()

此外,您在工作线程中使用相同的锁定基本上序列化所有计算,这违背了线程的目的。您正在处理的问题是CPU绑定,多线程不会在python中为您提供任何加速。看看multiprocessing模块。使用multiprocessing.Pool.map()(或其他一些map方法)可以大大简化整个程序,并通过mutliprocessig同时加快速度。