简体   繁体   English

使用Flask-Script / Python从标准输入读取

[英]Reading from standard input using Flask-Script / Python

Right now I have flask-script command that takes a path as an argument, then reads from the path: 现在我有flask-script命令,它以路径作为参数,然后从路径读取:

@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: 我尝试使用fileinput.input() ,通过此https://stackoverflow.com/a/1454400/1164573 ,使用以下内容调用:

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

But fileinput.input() is empty. 但是fileinput.input()是空的。 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
)

works for my simple test. 适用于我的简单测试。 . . assuming you're using bash for your shell at least. 假设你至少使用bash作为你的shell。 I only use bash, so don't know if this syntax works for other shells. 我只使用bash,所以不知道这种语法是否适用于其他shell。

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. 或者,您可以测试特殊值的文件名值,通常-如果这是要读取的文件的名称,则使用sys.stdin

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

for line in f:
    print line

and so forth 等等

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM