Search code examples
pythonbashpexpect

Python: pexpect does not execute `backtick` command


I'm trying to run this command:

foo=`ls /`

Works perfectly on bash but not if I execute it via pexpect:

p = pexpect.spawn("foo=`ls /`").interact()

// Gives error command was not found or not executable: foo=`ls

What is the cause and how do I fix it? I've even tried escaping the ` but it seems its not working.


Solution

  • The command you are trying to execute requires bash. pexpect does not pass your command through bash, instead invoking your executable directly as if it were the shell.

    From the docs:

    Remember that Pexpect does NOT interpret shell meta characters such as redirect, pipe, or wild cards (>, |, or *). This is a common mistake. If you want to run a command and pipe it through another command then you must also start a shell. For example:

    child = pexpect.spawn('/bin/bash -c "ls -l | grep LOG > log_list.txt"')
    child.expect(pexpect.EOF)
    

    Although the documentation doesn't mention them, this would certainly also apply to backticks. So write your code to invoke bash explicitly:

    p = pexpect.spawn('/bin/bash -c "foo=`ls /`"').interact()