Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Using Databases in Python Gettin' CRUD-y With It Add An Entry

John Caraballo
John Caraballo
19,943 Points

EOF Error on adding an entry

So as the title says I'm getting an EOF error every time I hit ctrl+d on Windows. I'm doing the excersise on the IntelliJ Idea IDE using python 3.4.2 I believe.

This is my code:

__author__ = 'John'

from collections import OrderedDict
import datetime
import sys

from peewee import *

db = SqliteDatabase('diary.db')


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

    class Meta:
        database = db


def initialize():
    """Create the database and the table if they don't exist"""
    db.connect()
    db.create_tables([Entry], safe=True)


def menu_loop():
    """Show the 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? [Y/N ").lower() != 'n':
            Entry.create(content=data)
            print("Saved succesfully")


def view_entries():
    """View previous entries."""


def delete_entry(entry):
    """Delete an entry."""

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


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

And this is the error:

Action: a
Enter your entry. Press ctrl+d when finished.
A new entr
Some new lines Save entry? [Y/N Traceback (most recent call last):
  File "E:/Python Projects/Python-Databases/src/diary.py", line 67, in <module>
    menu_loop()
  File "E:/Python Projects/Python-Databases/src/diary.py", line 38, in menu_loop
    menu[choice]()
  File "E:/Python Projects/Python-Databases/src/diary.py", line 47, in add_entry
    if input("Save entry? [Y/N ").lower() != 'n':
EOFError: EOF when reading a line

Process finished with exit code 1

3 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,029 Points

Hi John, I've run your code through various paths. I was able to reproduce your error under the following cases:

  1. After hitting "a" to add entry, enter text on a single line without EOL, I hit a Cntl-D twice to get to the "Save Entry" input, then a third Cntl-D causes the error you posted.
  2. After hitting "a" to add entry, enter text on a single line with EOL, I hit a Cntl-D once to get to the "Save Entry" input, then a third Cntl-D causes the error you posted.
  3. Hitting Cntl-D at the "Action" input causes similar error:
Action: Traceback (most recent call last):
  File "code.py", line 73, in <module>
    menu_loop()
  File "code.py", line 36, in menu_loop
    choice = input('Action: ').lower().strip()
EOFError

These error are caused by Cntl-D not being handled properly by your code. There are three points you need to catch a Cntl-D:

  1. Input of an new entry,
  2. At the "Save Entry" input, and
  3. At the "Action" input.

The first case is covered by the data = sys.stdin.read().strip() which is looking for a Cntl-D.

The second case can be handled by wrapping the "Save Entry" code with a try/except statement:

    if data:
        try:
            if input("Save entry? [Y/N ").lower() != 'n':
                Entry.create(content=data)
                print("Saved succesfully")
        except EOFError:
            print("save aborted")

The third case can be handled by wrapping "Action" code with a similar try/except statement:

        try:
            choice = input('Action: ').lower().strip()
        except EOFError:
            # Print blank line. Menu will reprint with quit instructions
            print("\n")

This should give you the Cntl-D handling you wish. Please post your results.

Vitaly Myshlaev
Vitaly Myshlaev
5,883 Points

I also had the same EOF error. I'm using PyCharm (Community Edition for Mac) for learning:

Traceback (most recent call last): Save entry? [Y]/n File "/Users/Documents/Code/Learning Python/dairy.py", line 67, in <module> menu_loop() File "/Users/Documents/Code/Learning Python/dairy.py", line 37, in menu_loop menuchoice File "/Users/Documents/Code/Learning Python/dairy.py", line 46, in add_entry if input('Save entry? [Y]/n ').lower() != 'n': EOFError: EOF when reading a line Process finished with exit code 1

So I've just changed the add_entry() to get multiple line entry, as stdin is the topic of the course:

def add_entry():
    """Add an entry."""
    entry = ""
    print("Log you idea, print 'done' to finish.")
    while True:
        data = input('> ')
        if data.lower() != 'done':
            entry += data + "\n"
        else:
            break
    # data = sys.stdin.read().strip()

    if entry:
        if input('Save entry? [Y]/n ').lower() != 'n':
            Entry.create(content=entry)
            print("Saved!")
        else:
            print("Your entry wasn't save")

And now it works well and helps me keep learning.

Laurens Sandt
Laurens Sandt
3,513 Points

Hi Chris I have the same problem.

The second solution gives me an EOFError:

Action: Traceback (most recent call last): File "C:/Users/Antonina/PycharmProjects/PeeWee/diary.py", line 67, in <module> menu_loop() File "C:/Users/Antonina/PycharmProjects/PeeWee/diary.py", line 32, in menu_loop choice = input("Action: ").lower().strip() EOFError: EOF when reading a line

The third solution gives me an infinite loop.