简体   繁体   中英

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.

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']

从sys.stdin读取,这是一个像object的文件

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