5

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

mkrieger1
  • 19,194
  • 5
  • 54
  • 65
Haohan Wang
  • 607
  • 2
  • 9
  • 25

2 Answers2

4

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.

ekhumoro
  • 115,249
  • 20
  • 229
  • 336
isedev
  • 18,848
  • 3
  • 60
  • 59
1

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.

Austin Phillips
  • 15,228
  • 2
  • 51
  • 50