我正在写一些代码,我有一个问题。我有我写的功能正常,但主循环(应该无限制地工作)只能正确工作一次。这是代码:
while 1==1:
choice=int(raw_input("press 1 for encrypt, 2 for decrypt"))
if choice==1:
string=raw_input("please enter plaintext here\n")
print('cipher-text follows and was copied to clipboard "'+encrypt_string(string))+'"'
elif choice==2:
string=raw_input("please enter cipher-text here\n")
print('plaintext follows : "'+decrypt_string(string))+'"'
else:
print("please enter a valid option")
问题在于整个循环工作一次,但随后它继续跳过raw_Input命令并抛出一个值错误。我不明白为什么会这样做。任何想法?
编辑,错误:
Traceback (most recent call last):
File "C:\Users\Raffi\Documents\python\encryptor.py", line 37, in <module>
choice=int(raw_input("press 1 for encrypt, 2 for decrypt"))
ValueError: invalid literal for int() with base 10: ''
答案 0 :(得分:0)
似乎(根据jme的评论)当你将文本粘贴到终端时,有多个换行符会导致程序继续为下一个raw_input
命令输入任何内容。 earlier question提供了几种可能的解决方案:
(1)使用sys.stdin.read()
:
print("please enter plaintext here\n")
text = sys.stdin.read()
然而,您必须按Ctrl Z / Ctrl D表示您已完成文本输入。
(2)使用Tk.clipboard_get
或类似命令直接从剪贴板中读取。
from Tkinter import Tk
root = Tk()
root.withdraw()
...
text = raw_input('Please enter plain text or just press enter to copy from the clipboard\n')
if not text:
text = root.clipboard_get()
(3)您还可以继续允许输入,直到输入空白行或其他标记文本结尾的方式。
print('Please enter plain text. Enter "stop" when you are finished')
text = ''
while True:
inp = raw_input()
if inp == 'stop':
break
text += inp
当然,这假设在您要复制的文本中没有“停止”的行。