使用Flask-Script/Python从标准输入中读取 [英] Reading from standard input using Flask-Script / Python
问题描述
现在我有flask-script命令,该命令将路径作为参数,然后从路径中读取:
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.)
我该怎么做?
我尝试通过 https://stackoverflow.com使用 fileinput.input()
/a/1454400/1164573 ,并通过以下方式调用:
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
但是 fileinput.input()
为空.这是因为flask-script包装了我的函数,并且没有直接向其中公开标准吗?我该如何解决?
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?
推荐答案
您几乎可以像您的示例那样进行操作,但是可以使用进程替换而不是管道:
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
)
适用于我的简单测试...假设您至少在外壳上使用bash.我只使用bash,所以不知道此语法是否适用于其他shell.
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.
或者,您可以测试文件名的值是否为特殊值,通常为-
,如果这是要读取的文件名,则使用 sys.stdin
.
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
以此类推
这篇关于使用Flask-Script/Python从标准输入中读取的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!