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.
On a command line, redirection is the process of using the input/output of a file or command to use it as an input for another file. It is similar but different from pipes, as it allows reading/writing from files instead of only commands. Redirection can be done by using the operators > and >> .
In Linux, for redirecting output to a file, utilize the ”>” and ”>>” redirection operators or the top command. Redirection allows you to save or redirect the output of a command in another file on your system. You can use it to save the outputs and use them later for different purposes.
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']
read from sys.stdin, which is a file like object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With