Reading from standard input using Flask-Script / Python

痴心易碎 提交于 2019-12-12 12:35:32

问题


Right now I have flask-script command that takes a path as an argument, then reads from the path:

@manager.option('-f', '--file', dest='file_path')
def my_command(file_path):
     open(file_path)
     ...

I'd want it to be able to read from standard in as well. (I frequently need to pass it text on the clipboard, and it's annoying to have to create a file each time.)

How can I accomplish this?

I've tried using fileinput.input(), via this https://stackoverflow.com/a/1454400/1164573, invoked with the following:

cat << EOF | ./manage.py my_command
abc
def
ghi
EOF

But fileinput.input() is empty. Is this because flask-script is wrapping my function and not exposing standard in to it directly? How can I get around this?


回答1:


You could do it almost like your example, but using process substitution instead of a pipe:

./manage.py my_command <(cat <<EOF
abc
def
ghi
jkl
EOF
)

works for my simple test. . . assuming you're using bash for your shell at least. I only use bash, so don't know if this syntax works for other shells.

Alternately, you could test the value of the filename for a special value, typically - and use sys.stdin if that's the name of the file to read.

if(sys.argv[1] == '-'):
    f = sys.stdin
else:
    f = file(sys.argv[1])

for line in f:
    print line

and so forth



来源:https://stackoverflow.com/questions/32084321/reading-from-standard-input-using-flask-script-python

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