Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call a command line which includes both "echo" and "|" [duplicate]

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

like image 825
Haohan Wang Avatar asked Oct 05 '22 21:10

Haohan Wang


2 Answers

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)
  1. "|" is a shell meta-character, so you need to invoke subprocess.call with shell=True.

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

like image 104
isedev Avatar answered Oct 13 '22 09:10

isedev


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.

like image 32
Austin Phillips Avatar answered Oct 13 '22 10:10

Austin Phillips