问题
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!
回答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)
回答2:
This works for me:
>>> stdin, stdout = os.popen2("echo %s | grep 'test'" % 'some test param')
>>> print stdout.read()
some test param
>>>
回答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
回答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.)
来源:https://stackoverflow.com/questions/1847195/python-bash-pipe