[Tutor] Re: Can I hook a "file" to a python script?

Roger Merchberger zmerch at 30below.com
Sat Nov 8 09:58:04 EST 2003


Rumor has it that Lee Harr may have mentioned these words:
>>I'd like a "file" on the Linux box to actually be the input and output
>>of a Python script.  Anything written to the file would be sent to a
>>database and anything read from the file would come from the database.
>>I know how to do the database end of this but I'm not sure if a script
>>can be hooked to a "file" transparently.

Okay... no problem...

>>   The script would probably have to be run as a daemon.

Probably, yes...

>>   I doubt there's enough magic in the Linux
>>world to make it so that a read/write would actually launch the script.

...You are actually quite incorrect with that statement, for a couple of 
reasons:

1) If the script is a daemon, it's running *all the time* so you won't need 
to 'launch' it every time...

2) There *is* more than enough magic in *nix (Linux, Unix, Xenix, etc... 
;-) to allow you to do this: it's called a named pipe.

Do you know how to redirect stdin & stdout from the command line?

bash# mycommand.py < inputfile.txt | nextcommand.py > outputfile.txt

This runs mycommand.py, but takes all input from inputfile.txt instead of 
from the keyboard or standard input. The center character is a "Pipe" 
character - it pipes the output from mycommand.py directly to the standard 
input of nextcommand.py which does it's magic, but instead of the output 
going to the screen or terminal window, it's sent to outputfile.txt.

(If you wanted to append the data to the file, instead of overwrite the 
file every time, use the two &gt; signs, like this:
   nextcommand.py >> outputfile.txt )

So, you want to set up a named pipe (or FIFO), and tell your daemon to take 
input from that. Then the daemon will sit there, and wait... and when you 
send data to the named pipe, it will automatically be sent to the waiting 
daemon, which will "do it's magic" when the data arrives.

1 Caveat - I've used them *Very* rarely, so I'm no exspurt on them, but 
here's a few links that can help...

http://www.linuxvalley.it/encyclopedia/ldp/manpage/man4/fifo.4.php

http://www.linuxjournal.com/article.php?sid=2156

Googling for '''linux named pipe tutorial'''  may well render other good 
help sites... ;-)

Hope this helps,
Roger "Merch" Merchberger

--
Roger "Merch" Merchberger -- sysadmin, Iceberg Computers
zmerch at 30below.com

What do you do when Life gives you lemons,
and you don't *like* lemonade?????????????




More information about the Tutor mailing list