簡體   English   中英

如何在python中使用sys.stdin.read()

[英]how to use sys.stdin.read() in python

我正在嘗試使用peewee模塊將多個文本用戶輸入到db中,但是當我在控制台中按ctrl + d時,它給了我EOFError。我認為問題出在sys.stdin.read()上。 ? 這是代碼:

#!/user/bin/env python3
from peewee import *

import sys
import datetime
from collections import OrderedDict

db = SqliteDatabase('diary.db')


class Entry(Model):
    content = TextField()
    timestamp = DateTimeField(default=datetime.datetime.now)  # no ()

    class Meta:
        database = db

def intitalize():
    '''create database and table if not exists'''
    db.connect()
    db.create_tables([Entry], safe=True)

def menu_loop():
    '''show menu'''
    choice = None

    while choice != 'q':
        print("enter 'q' to quit")
        for key, value in menu.items():
            print('{}) {}'.format(key, value.__doc__))
        choice = input('action: ').lower().strip()

        if choice in menu:
            menu[choice]()

def add_entry():
    '''add an entry'''
    print("Enter your entry. press ctrl+d when finished")
    data = sys.stdin.read().strip()

    if data:
        if input('Save Entry?[Yn]').lower()!='n':
            Entry.create(content=data)
            print('saved successfully')

def view_entry():
    '''view entries'''

def delete_entry():
    '''delete an entry'''


menu = OrderedDict([
    ('a', add_entry),
    ('v', view_entry),
])


if __name__ == '__main__':
    intitalize()
    menu_loop()   

這是我在pycharm中遇到的錯誤:

enter 'q' to quit
a) add an entry
v) view entries
action: a
Enter your entry. press ctrl+d when finished
some text
and more
^D
Save Entry?[Yn]Traceback (most recent call last):
  File "C:/Users/Xylose/Desktop/small lab/peewee/venv/dairy.py", line 61, in <module>
    menu_loop()
  File "C:/Users/Xylose/Desktop/small lab/peewee/venv/dairy.py", line 34, in menu_loop
    menu[choice]()
  File "C:/Users/Xylose/Desktop/small lab/peewee/venv/dairy.py", line 42, in add_entry
    if input('Save Entry?[Yn]').lower()!='n':
EOFError: EOF when reading a line

Process finished with exit code 1

在Python中

EOFError: EOF when reading a line 

此錯誤有2個原因

1.以錯誤的方式/格式讀取文件

 import sys
 for line in sys.stdin:
     print (line)

這就是我們如何使用“ sys.stdln”進行閱讀的方法

2.如果文件損壞,則有另一個機會發生相同的錯誤

通常允許在Ctrl-D之后從stdin讀取,但是我僅在Ubuntu上進行了測試(與您的代碼相似的代碼運行良好)。 我看到它正在Windows上運行,並且Windows控制台的行為可能有所不同,並在Ctrl-D之后拒絕任何read()操作。 一種可能的解決方案是使用try / except語句捕獲EOFError異常,並在異常發生時關閉並重新打開sys.stdin。 像這樣:

# note: check that sys.stdin.isatty() is True!

try:
    # read/input here

except EOFError:

    sys.stdin.close()
    sys.stdin = open("con","r")
    continue # or whatever you need to do to repeat the input cycle

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM