Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How redirect a shell command output to a Python script input ?

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.

like image 924
delta Avatar asked Dec 12 '11 17:12

delta


People also ask

How do I redirect output to input?

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 >> .

How do you redirect the output of a command to a file in Linux?

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.


2 Answers

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']
like image 63
DhruvPathak Avatar answered Oct 05 '22 08:10

DhruvPathak


read from sys.stdin, which is a file like object

like image 45
zchenah Avatar answered Oct 05 '22 07:10

zchenah