简体   繁体   中英

Can I make a program reading from a piped stdin AND keyboard?

Can I write a python program that read from a piped stdin and keyboard?

What I mean? I want to be able to use it in this way:

tail -f LOGFILE | myscript.py

see the log lines appearing in the screen and type commands with the keyboard?

This sounds like 2 stdin and that confuse me. Is it possible or is it conceptually wrong?

Thanks!

Possible solution would be to grab the users current tty and attach a file stream to the corresponding /dev/tty entry.

This may allow you to grab the keyboard input while using stdin as your piped log file.

Make your script take a file argument, then use bash's ability to create an anonymous fifo:

myscript.py <( tail -f LOGFILE )

bash translates this to (roughly):

mkfifo /tmp/UNIQUEFILENAME
tail -f LOGFILE > /tmp/UNIQUEFILENAME &
myscript.py /tmp/UNIQUEFILENAME

Have only the commands come through stdin.

<() and >(), especially when combined with tee, can be used anytime you want to create a "branch" in an either side of an arbitrary bash pipeline.

This might be hackable, but it is conceptually wrong seems weird to me. stdin is a single input stream. Issuing the command

... | program.py

changes stdin to be the stdout of whatever came before the pipe. But accepting keyboard input means reading the original stdin -- you can't have your cake and eat it too!

A hack would merge those two streams into one, but that's not a good way of doing it; it doesn't separate the data correctly. If your program really should accept keyboard input as well as piped data (are you sure that it should? that seems like an awfully counterintuitive thing to want!), the right way to do it is to spawn separate threads to handle each of the input streams.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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