Reading from standard input using Flask-Script / Python

661 Views Asked by At

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

There are 1 best solutions below

0
On

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