Reputation: 171
This is probably something really basic, but I can not find a good solution for it. I need to write a python script that can accept input from a pipe like this:
$ some-linux-command | my_script.py
something like this:
cat email.txt | script.py
Or it will just be piped by my .forward file directly from sendmail. This means that the input file might be something relatively large if it has an attachment, and it will probably be an e-mail, later I will have to put in a database the sender, the subject and such, but I have written database scripts in python, so that part will be OK. The main problem is how to capture the data flowing in from the pipe.
Upvotes: 17
Views: 18330
Reputation: 43265
Use sys.stdin to read the input . Example :
Example content of s.py :
import sys
data = sys.stdin.readlines()
print data
-- Running :
user@xxxxxxx:~$ cat t.txt
alpha
beta
gamma
user@xxxxxxx:~$ cat t.txt | python ./s.py
['alpha\n', 'beta\n', 'gamma\n']
You can also make the python script as shell script using this Shebang :
#!/usr/bin/env python
and changing permission to 'a+x'
user@xxxxxxx:~$ cat t.txt | ./s.py
['alpha\n', 'beta\n', 'gamma\n']
Upvotes: 28