2017-10-07 57 views
1

我使用以下代碼中的行讀取:停止當EOF在線的Python

for line in sys.stdin: 
    print('Output: ', end='') 
    print(line.rstrip('\n')) 

作爲輸入我看到輸出如:

test 
Output: test 
another test 
Output: another test 
eof at end of line^DOutput: eof at end of line 
I can still type here 
Output: I can still type here 
... 

在這種情況下^D裝置鍵入CTRL- D或EOF字符。

我的程序應該在一個EOF發生在一行的結尾而不是一行中唯一的字符時結束。我怎樣才能得到這種行爲?

實例行爲:

test 
Output: test 
another test 
Output: another test 
eof at end of line^DOutput: eof at end of line 
[program terminates] 

回答

0

你不提你的操作系統,但它是Linux或UNIX的另一個變種我敢打賭。

這裏的訣竅是^ D本身並不是EOF標記。相反,讀取輸入的驅動程序將^ D標識爲信號文件的結尾,因此會關閉將終端連接到您的程序的文件,從而產生EOF條件。

然而,踢球者只是在隊列中的第一個字符時,司機纔會解釋^ D,以防某人真的想要輸入^ D。所以,這將很難做到,但這並不是說你的程序有問題 - 你只是看到了意想不到的但正常的行爲。

+0

終端驅動程序不關閉流,它始終解釋'^ D'。但它只是讓'read(2)'返回,它只返回0時暗示EOF。 –

+0

有什麼方法可以實現我想要的行爲?我知道在C中,我可以使用像'while(getline(&line,&n,stdin)!= -1)'這會產生我預期的行爲。 – carloabelli