Reputation: 1477
I,m trying to save multiple texts user enter in a db using peewee module but it give me EOFError when i press ctrl+d in console.I think problem is whit sys.stdin.read().anyway can anyone help me fix this? here is the code:
#!/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()
here is error i get in 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
Upvotes: 0
Views: 5220
Reputation: 836
in Python the
EOFError: EOF when reading a line
there is 2 reason for this error
1.reading the file in the wrong way/format
import sys
for line in sys.stdin:
print (line)
this how we can read using "sys.stdln"
2.there is another chance for the same error if the file is corrupted
Upvotes: 3
Reputation: 5354
Reading from stdin after Ctrl-D is normally allowed, but I have tested this only on Ubuntu (code similar to yours works perfectly well). I see that this is being run on Windows and the Windows console might behave differently and refuse any read() operations after Ctrl-D. One possible solution is to capture the EOFError
exception with a try/except statement and close and re-open sys.stdin when the exception occurs. Something like this:
# 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
Upvotes: 1