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

how to use sys.stdin.read() in python

我正在尝试使用 peewee 模块保存用户在数据库中输入的多个文本,但是当我在 console.I 中按 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.reading文件中的错误way/format

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

这是我们如何使用 "sys.stdln"

阅读

2.there 如果文件已损坏

是另一个出现相同错误的机会

通常允许在 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