简体   繁体   English

继续阅读sys.stdin

[英]Continue reading on sys.stdin

Is it possible to continue reading input on sys.stdin ? 是否可以继续读取sys.stdin输入? I'm trying to continuously execute a function based on input. 我试图基于输入连续执行一个功能。 (My function only prints to sys.stdout and sys.stderr , and doesn't return anything.) My Code: (我的函数仅输出到sys.stdoutsys.stderr ,并且不返回任何内容。)我的代码:

def prime(number):
    number = abs(int(number))
    for i in range(3, number):
        if number % i == 0:
            print("Not Prime!", file = sys.stderr, flush = True)
            sys.exit(0)
    print("Prime!", file = sys.stdout, flush = True)

for i in sys.stdin:
    prime(i)

Here's the output: 这是输出:

>>> for i in sys.stdin:
        prime(i)
43         # Input
Prime!     # In sys.stdout and it continues reading from sys.stdin
55         # Input
Not Prime! # In sys.stderr and stops.
>>>

I've tested it out and determined that it continues reading when the output of my function is on sys.stdout and stops when outputting on sys.stderr . 我已经对其进行了测试,并确定在我的函数的输出在sys.stdout上时它将继续读取,而在sys.stderr上的输出时它将停止读取。

Well after you print 'Not prime' to sys.stderr you make a call to sys.exit which causes your program to terminate. 在对sys.stderr打印“ Not prime”后,您将调用sys.exit ,这将导致程序终止。 If you remove this, reading on sys.stdin should continue until you issue an EOF character (Ctrl+Z on Windows, Ctrl+D on POSIX). 如果删除此选项,则应继续进行sys.stdin读取,直到发出EOF字符(在Windows上为Ctrl + Z,在POSIX上为Ctrl + D)。

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

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