简体   繁体   English

从PExpect使用重新定义的命令

[英]Use Redefined command from PExpect

How can I redefine a command in a bash script so that a python script called from the bash script will execute the redefined version when called via pexpect? 如何在bash脚本中重新定义命令,以便从bash脚本调用的python脚本在通过pexpect调用时将执行重新定义的版本?

test.sh test.sh

#!/bin/bash
function scp(){
    echo "Skip SCP"
}
export -f scp
python test.py

test.py test.py

import pexpect
scp = pexpect.spawn("scp")
scp.expect([pexpect.EOF,pexpect.TIMEOUT],timeout=1500)
print scp.before    

In this example I expect (and want) to see is: 在此示例中,我希望(并且希望)看到的是:

Skip SCP 跳过SCP

but what I actually see is: 但是我实际看到的是:

usage: scp [-1246BCpqrv] [-c cipher] [-F ssh_config] [-i identity_file]
           [-l limit] [-o ssh_option] [-P port] [-S program]
           [[user@]host1:]file1 ... [[user@]host2:]file2

I can change anything about the shell script, but the python comes from a third party and is copied into many different projects, so changing it would be impractical. 我可以更改有关shell脚本的任何内容,但是python来自第三方,并且已被复制到许多不同的项目中,因此更改它是不切实际的。

Most likely spawn executes it's commands directly (via execv or something) or it uses a specific shell like /bin/sh. spawn最有可能直接(通过execv或其他方式)执行其命令,或者使用诸如/ bin / sh之类的特定shell。 If you want it to use a customized environment, you'll have to specify that yourself. 如果要使用自定义环境,则必须自己指定。 I don't know pexpect, but something like 我不知道期望,但是类似

spawn bash
expect your_prompt
send "function scp { echo 'skip scp'; }"
expect your_prompt
send scp
expect "skip scp"

Additionally, bash functions are not exported to child processes unless you export -f scp 此外,除非您export -f scp否则bash函数不会导出到子进程。


Since you can't touch the pexpect part, the only thing you can change is scp . 由于您无法触摸预期部分,因此唯一可以更改的就是scp You will have to provide a program named "scp" that occurs earlier in the path than the regular scp 您将必须提供一个名为“ scp”的程序,该程序在路径中的出现时间比常规的scp更早

#!/bin/sh
PATH=/my/special/path:$PATH
cat > /my/special/path/scp <<END
#!/bin/sh
echo "no scp here!"
END
chmod 755 /my/special/path/scp

python test.py

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM