【发布时间】:2016-11-29 06:48:24
【问题描述】:
我正在使用线程和队列在 python 中编写一个简单的凯撒密码程序。即使我的程序能够运行,它也不会创建必要的输出文件。将不胜感激任何帮助,谢谢!
我猜异常开始于我使用队列存储加密字符串的地方,这里:
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())
这是完整的代码:
import threading
import sys
import Queue
import string
#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
#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()
#Thread tanimlamasi
class WorkingThread(threading.Thread):
def __init__(self):
threading.Thread.__init__(self)
def run(self):
lock.acquire()
q2.put(self.caesar(q1.get(), s))
lock.release()
def caesar(self, plaintext, shift):
alphabet = string.ascii_lowercase
shifted_alphabet = alphabet[shift:] + alphabet[:shift]
table = string.maketrans(alphabet, shifted_alphabet)
return plaintext.translate(table)
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()
【问题讨论】:
标签: python file queue output caesar-cipher