tags:

views:

251

answers:

4
+1  Q: 

Python bash pipe

I want to pipe a python script's output to a bash script. What i did so far was i tried to use os.popen(), sys.subprocess(), and tried to give a pipe for an example

os.popen('echo "P 1 1 591336 4927369 1 321 " | v.in.ascii -zn out=abcx format=standard --overwrite')

but this didn't work, the values "591336" and "4927369" are the variables which comes as the output of the python script. but when I do this or change the values manually by repeating the echo command and the pipe, it works (in bash).

v.in.ascii -zn out=abcx format=standard --overwrite

the above part of the bash command is a part of Grass GIS

Can anyone help me!

+4  A: 

You can just use print to output to stdout and pipe the Python process to the next process, e.g.

python myprogram.py | ...

Where myprogram.py might look like:

for x in something:
    print dosomething(x)
John Paulett
+1  A: 

This works for me:

>>> stdin, stdout = os.popen2("echo %s | grep 'test'" % 'some test param')
>>> print stdout.read()
some test param

>>>
vvatsa
A: 

I really like John Paulett's answer.

I think your echo example would work if you used os.system instead of os.popen.

One way to use popen here is like this:

f = os.popen("v.in.ascii -zn out=abcx format=standard --overwrite", 'w')
f.write("P 1 1 591336 4927369 1 321\n")
f.close()

(You have to specify the pipe is for writing.)

Jason Orendorff
+1  A: 

As of Python 2.6, the subprocess module is recommended instead of the deprecated os.popen. Here's an example:

from subprocess import Popen, PIPE
p = Popen(["v.in.ascii", "-zn", "out=abcx", "format=standard", "--overwrite"], stdin=PIPE)
p.stdin.write("P 1 1 591336 4927369 1 321\n")
p.stdin.close()
p.wait() # unless background execution preferred
akaihola
this is the bash command i use to do the reading temporarily #!/bin/bashd.mon x1d.rast elevation.demd.vect abcx d.vect abcy #value=0;while read linedo#value=`expr $value + 1`;echo $lineecho $lineecho "P 1 1$line 1 321 " | v.in.ascii -zn out=abcx format=standard --overwrited.redraw #sleep 1done < "cordvals.txt"this cordvals.txt is created from the variables which is written by the python script if i can change this it will be ok too (to put the python script's output as the input to this while loop)