Read input from StdIn when redirecting StdIn to py

2019-08-08 08:19发布

问题:

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.