按照评论中的建议,使用
pexpect
。
看见
pexpect on github
,则,
the official docs
和
this handy python for beginners walkthrough on pexpect
。
例如。假设这是你的
x.sh
文件:
#!/bin/bash
echo -n "Continue? [Y/N]: "
read answer
if [ "$answer" != "${answer#[Yy]}" ]; then
echo -n "continuing.."
else
echo -n "exiting.."
fi
您可以这样做:
import os, sys
import pexpect
# It's probably cleaner to use an absolute path here
# I just didn't want to include my directories..
# This will run x.sh from your current directory.
child = pexpect.spawn(os.path.join(os.getcwd(),'x.sh'))
child.logfile = sys.stdout
# Note I have to escape characters here because
# expect processes regular expressions.
child.expect("Continue\? \[Y/N\]: ")
child.sendline("Y")
child.expect("continuing..")
child.expect(pexpect.EOF)
print(child.before)
python脚本的结果:
Continue? [Y/N]: Y
Y
continuing..
尽管我不得不说,如果您有能力编辑它,那么将pexpect与bash脚本一起使用是有点不寻常的。编辑脚本会更简单,这样它就不再提示:
#!/bin/bash
echo -n "Continue? [Y/N]: "
answer=y
if [ "$answer" != "${answer#[Yy]}" ]; then
echo "continuing.."
else
echo "exiting.."
fi
那你就可以自由使用
subprocess
执行它。
import os
import subprocess
subprocess.call(os.path.join(os.getcwd(),"x.sh"))
或者,如果希望将输出作为变量:
import os
import subprocess
p = subprocess.Popen(os.path.join(os.getcwd(),"x.sh"), stdout=subprocess.PIPE)
out, error = p.communicate()
print(out)
我意识到这对你来说可能不可能,但值得一提。