简体   繁体   English

Python 当我将多行文本粘贴到输入提示时脚本死掉

[英]Python script dies when I paste multiline text into input prompt

I made a program:我做了一个程序:

import collections
x = input("Enter in text: ")
x_counter = collections.Counter()
x_counter.update(x)
print("Your sequence contains:\n")
for i in '`1234567890-=qwertyuiop[]\asdfghjkl;zxcvbnm,./~!@#$%^&*()_+QWERTYUIOP\
{}|ASDFGHJKL:"ZXCVBNM<>?':
    print(i, x_counter[i])

That prints out the number of times a letter has been used in a text.这会打印出一个字母在文本中被使用的次数。 When the user enters in a smaller sized text, like a paragraph for example...the program runs fine.当用户输入较小的文本时,例如一段文字……程序运行良好。 When the user enters a very long text, say 5 paragraphs...the program quits and runs all of the input as bash commands...Why is this???当用户输入很长的文本时,比如 5 段……程序退出并以 bash 命令运行所有输入……这是为什么???

That's because input only gets a single line from the user, as per the following example:这是因为input仅从用户那里获取一行,如以下示例所示:

pax> cat qq.py
x = raw_input ("blah: ") # using raw_input for Python 2
print x

pax> python qq.py
blah: hello<ENTER>
hello

pax> there<ENTER>
bash: there: command not found

pax> 

One possibility is to read the information from a file rather than using input , but you can also do something like:一种可能性是从文件中读取信息而不是使用input ,但您也可以执行以下操作:

def getline():
    try:
        x = raw_input ("Enter text (or eof): ")
    except EOFError:
        return ""
    return x + "\n"

text = ""
line = getline()
while line != "":
    text = text + line;
    line = getline()
print "\n===\n" + text

which will continue to read input from the user until they end the input with EOF (CTRL-D under Linux):它将继续读取用户的输入,直到他们以 EOF(Linux 下的 CTRL-D)结束输入:

pax> python qq.py
Enter text (or eof): Hello there,
Enter text (or eof): 
Enter text (or eof): my name is Pax.
Enter text (or eof): <CTRL-D>
===
Hello there,

my name is Pax.

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

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