2

Is it possible to continue reading input on 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:

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.

Zizouz212
  • 4,908
  • 5
  • 42
  • 66
  • Just to make sure: Do you want to output the result to your terminal and then use that as your input again? If not, how does a call to your script looks like? How is it getting the `43` and the `55`? – Savir Mar 10 '15 at 15:22
  • So, I'm using IDLE, and I'm just using `stderr` and `stdout` to get colours. And the code that I am using to get input in my function is exactly how it looks in the question. I'll make an edit with my function's code. – Zizouz212 Mar 10 '15 at 15:23

1 Answers1

5

Well after you print 'Not prime' to sys.stderr you make a call to sys.exit which causes your program to terminate. If you remove this, reading on sys.stdin should continue until you issue an EOF character (Ctrl+Z on Windows, Ctrl+D on POSIX).

Jed Estep
  • 585
  • 1
  • 4
  • 15