我对 python 和线程还很陌生。我正在尝试编写一个使用线程和队列的程序,以便使用凯撒密码加密 txt 文件。当我单独使用加密函数时,它本身运行良好,但在我的程序中使用它时出现错误。错误从这一行开始:
for c in plaintext:
这里是完整的代码:
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()
非常感谢任何帮助,在此先感谢。
请您参考如下方法:
在您的代码中,您使用的是函数对象 q1.get 和 q2.get。而是用括号调用它:
q1.get()
将从 Queue 中获取值.
根据 Queue.get() document :
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.
