I tried to use Python to call the command line to execute some files. However, when there is a command line containing both echo
and |
, the subprocess.call
seems not working very well. Like
when I run:
echo "perp -t ../data/ReviewTest.text" | ./eva -b ../data/6.binlm
I will get what I want. However, when I try this:
import subprocess
e=["echo","\"perp", "-t", "../data/R.text\"", "|", "./eva", "-b", "../data/6.binlm"]
subprocess(e)
I will get everything except echo showed in command line like:
".prep -t ..data/ReviewTest.text" | ./eva -b ../data/6.binlm
It seems that in subprocess.call()
, when there is an echo
, everything after it will just be thrown out onto the command line.
I hope there is some solution for me to use subprocess
when a command contains both echo
and |
.
I think this might achieve the effect you are looking for (it should reproduce exactly the first command line listed in your question):
>>> import subprocess
>>> e = 'echo "perp -t ../data/ReviewTest.text | ./eva -b ../data/6.binlm'
>>> subprocess.call(e, shell=True)
"|" is a shell meta-character, so you need to invoke subprocess.call
with shell=True
.
In the command line, you are passing the string "perp -t ../data/ReviewTest.text"
as the first and only argument of echo
, so you need to pass the same string and not just individual components in the subprocess.call
argument string.
The pipe |
is a shell construct meaning that the command needs to be run as input to a shell. This means setting shell=True
when subprocess.call()
is called.
import subprocess
subprocess.call("""echo "perp -t ../data/ReviewTest.text" | ./eva -b ../data/6.binlm""", shell=True)
There are notes about using shell=True in the Python docs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With