简体   繁体   English

for循环中的sys.stdin无法获取用户输入

[英]sys.stdin in for loop is not grabbing user input

I have this code ( test.py ) below: 我在下面有此代码( test.py ):

import sys    
for str in sys.stdin.readline():
    print ('Got here')
    print(str)

For some reason when I run the program python test.py and then I type in abc into my terminal I get this output: 由于某种原因,当我运行程序python test.py ,然后在终端中输入abc我得到以下输出:

>>abc
THIS IS THE OUTPUT:
Got here
a
Got here
b
Got here
c
Got here

It prints out Got here five times and it also prints out each character a , b , c individually rather than one string like abc . Got here打印了五次,并且分别打印了每个字符abc而不是像abc这样的一个字符串。 I am doing sys.stdin.readline() to get the entire line but that doesn't seem to work either. 我在做sys.stdin.readline()以获取整行,但这似乎也不起作用。 Does anyone know what I am doing wrong? 有人知道我在做什么错吗?

I am new to python and couldn't find this anywhere else on stackoverflow so sorry if this is a obvious question. 我是python的新手,在stackoverflow的其他任何地方都找不到它,所以很抱歉,如果这是一个明显的问题。

readline() reads a single line. readline()读取一行。 Then you iterate over it. 然后您遍历它。 Iterating a string gives you the characters, so you are running your loop once for each character in the first line of input. 迭代字符串会为您提供字符,因此对于输入的第一行中的每个字符,您都要运行一次循环。

Use .readlines(), or better, just iterate over the file: 使用.readlines()或更好的方法是,仅遍历文件:

for line in sys.stdin:

But the best way to get interactive input from stdin is to use input() (or raw_input() in Python 2). 但是,从stdin获取交互式输入的最好方法是使用input() (或Python 2中的raw_input() )。

You are looping through each character in the string that you got inputted. 您正在遍历输入字符串中的每个字符。

import sys    
s = sys.stdin.readline()
print ('Got here')
print(s)

# Now I can use string `s` for whatever I want
print(s + "!")

In your original code you got a string from stdin and then you looped through ever character in that input string and printed it out (along with "Got here"). 在原始代码中,您从stdin获得了一个字符串,然后循环遍历该输入字符串中的ever字符并将其打印出来(以及“ Got here”)。

EDIT: 编辑:

import sys
while True:
    s = sys.stdin.readline()

    # Now I can do whatever I want with string `s`
    print(s + "!")

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

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