简体   繁体   English

TypeError:'instancemethod'对象不可迭代(Python)

[英]TypeError: 'instancemethod' object is not iterable (Python)

I am pretty new with python and threading. 我对python和线程很陌生。 I am trying to write a program which uses threads and queues in order to encrypt a txt file using caesar cipher. 我试图编写一个使用线程和队列的程序,以便使用凯撒密码对txt文件进行加密。 The encrypting function works well on its own when I use it exclusively, but I get an error when I use it in my program. 当我单独使用加密功能时,加密功能本身可以很好地工作,但是在程序中使用它时会出错。 The error starts from this line: 错误从此行开始:

for c in plaintext:

And here is the whole code: 这是整个代码:

import threading
import sys
import Queue

#argumanlarin alinmasi
if len(sys.argv)!=4:
    print("Duzgun giriniz: '<filename>.py s n l'")
    sys.exit(0)
else:
    s=int(sys.argv[1])
    n=int(sys.argv[2])
    l=int(sys.argv[3])

#Global
index = 0

#caesar sifreleme


#kuyruk deklarasyonu
q1 = Queue.Queue(n)
q2 = Queue.Queue(2000)


lock = threading.Lock()

#Threadler
threads=[]

#dosyayi okuyarak stringe cevirme
myfile=open('metin.txt','r')
data=myfile.read()


def caesar(plaintext, key):
    L2I = dict(zip("ABCDEFGHIJKLMNOPQRSTUVWXYZ", range(26)))
    I2L = dict(zip(range(26), "ABCDEFGHIJKLMNOPQRSTUVWXYZ"))

    ciphertext = ""
    for c in plaintext:
        if c.isalpha():
            ciphertext += I2L[(L2I[c] + key) % 26]
        else:
            ciphertext += c
    return ciphertext

#Thread tanimlamasi
class WorkingThread(threading.Thread):
    def __init__(self):
        threading.Thread.__init__(self)

    def run(self):
        lock.acquire()
        q2.put(caesar(q1.get, s))
        lock.release()

for i in range(0,n):
    current_thread = WorkingThread()
    current_thread.start()
    threads.append(current_thread)

output_file=open("crypted"+ "_"+ str(s)+"_"+str(n)+"_"+str(l)+".txt", "w")

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)

for i in range(0,n):
    threads[i].join()

output_file.close()
myfile.close()

Would appreciate any help, thanks in advance. 希望有任何帮助,在此先感谢。

In your code you are using q1.get and q2.get which are function objects. 在您的代码中,您使用的是函数对象q1.getq2.get Instead call it with parenthesis: 而是用括号来称呼它:

q1.get()

which will fetch the value from the Queue . 这将从Queue中获取值。

As per the Queue.get() document : 根据Queue.get()文件

Remove and return an item from the queue. 从队列中删除并返回一个项目。 If optional args block is true and timeout is None (the default), block if necessary until an item is available. 如果可选的args块为true,并且超时为None(默认值),则在必要时阻塞,直到有可用项为止。

You're passing Queue. 您正在传递队列。 get [the function] to caesar instead of the value from calling Queue. 使 [函数]凯撒而不是调用Queue的值。 get() . get()

Add some '()' and you should be fine. 添加一些“()”,你应该没问题。 :) :)

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

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