Read input from StdIn when redirecting StdIn to python manage.py shell

我的未来我决定 提交于 2019-12-11 05:36:15

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!