Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pipe out of a command or script to another python script

I'm relatively to to python and I'm trying to write a python script to which one can pipe the output of a command or another script.

example command | python_sript.py

In python script I'll basically analyze the output of command and save it to file.

I thought I'll be able to do this with redirecting sys.stdin to subprocess.PIPE, but it didn't work.

sys.stdin = subprocess.PIPE

Can some one please suggest how should I approach this?

Also what would happen if command or script pipes data at faster rate then what python script can process.

Note: When I use this script

import sys
data = sys.stdin.readline()
print(data)

I get this

D:\>echo "test" | tee.py
The process tried to write to a nonexistent pipe.
Traceback (most recent call last):
  File "D:\Profiles\Administrator\My Documents\Workspace\tee.py", line 3, in <mo
dule>
    data = sys.stdin.readline()
AttributeError: 'NoneType' object has no attribute 'readline'

and when I use this

import sys
data = input()
print(data)

I get this

D:\>echo "test" | tee.py
The process tried to write to a nonexistent pipe.
Traceback (most recent call last):
  File "D:\Profiles\Administrator\My Documents\Workspace\tee.py", line 3, in <mo
dule>
    data = input()
RuntimeError: input(): lost sys.stdin
like image 981
nik Avatar asked Sep 05 '26 06:09

nik


1 Answers

On (old) Windows when you use pipes you need to call python scripts using python executable by default due to NT redirection bug:

D:\> echo "test" | python tee.py

After that sys.stdin, raw_input(), fileinput.input() should work as expected.

like image 143
jfs Avatar answered Sep 07 '26 18:09

jfs



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!