2

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!

0

4 Answers 4

6

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)
Sign up to request clarification or add additional context in comments.

Comments

1

This works for me:

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

>>>

Comments

1

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

1 Comment

this is the bash command i use to do the reading temporarily #!/bin/bash d.mon x1 d.rast elevation.dem d.vect abcx d.vect abcy #value=0; while read line do #value=expr $value + 1; echo $line echo $line echo "P 1 1 $line 1 321 " | v.in.ascii -zn out=abcx format=standard --overwrite d.redraw #sleep 1 done < "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)
0

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

1 Comment

As mentioned before, os.system has been deprecated since Python 2.6. The newer (and supported) subprocess.call or subprocess.run methods work fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.