问题
I have a python script that I call redirecting it to Django manage.py shell
.
$ python manage.py shell < script.py
I want to take an answer from user to decide what to do. But I can't do it neither with input()
or sys.stdin.readline()
.
With input()
answer = input('A question')
if answer == 'y':
# Do something
else:
pass
Error:
EOFError: EOF when reading a line
With sys.stdin.readline:
answer = sys.stdin.readline()
if answer == 'y':
# Do something
else:
pass
In this case script continues without wait for user input.
What's the correct way for doing that?
回答1:
You're making ./manage.py shell
get some input, but the input you've provided was the contents of script.py
.
It would be a lot nicer to write a custom Django management command. For example:
from django.core.management.base import BaseCommand
class Command(BaseCommand):
def handle(self, *args, **options):
answer = input('A question')
if answer == 'y':
# Do something
else:
pass
which you would then call with manage.py my_script
.
来源:https://stackoverflow.com/questions/44728109/read-input-from-stdin-when-redirecting-stdin-to-python-manage-py-shell