Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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)

Solution 2:

This works for me:

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

>>>

Solution 3:

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

Solution 4:

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

Post a Comment for "Python Bash Pipe"