我想在python中打开一个bash会话,并继续与它进行交互,就好像它是一个终端。这是我到目前为止:
import subprocess as s
class Session:
proc = None
def execute(self, cmd):
if self.proc is None:
self.proc = s.Popen("/bin/bash", shell=True, stdin=s.PIPE, stdout=s.PIPE, stderr=s.STDOUT)
cmd = cmd + ' ; echo EOF\n'
self.proc.stdin.write(cmd.encode())
output = ''
while not output.endswith("EOF"):
output += self.proc.stdout.read(1).decode()
return output
sess = Session()
sess.execute("export MY_VAR=HELLO")
sess.execute("git clone https://github.com/internetsadboy/crapi.git")
但是,在git clone期间,我得到了这个输出,但它失败了
Cloning into 'crapi'...
EOF
好吧,完全免责声明,python可能是我的第一语言,但肯定不是我最好的
这应该让你开始:
self.execute("/bin/bash")#spawn a bash session
之后,您可以将命令管道化为bash。我不完全确定你想要实现的目标,但你可以在这里使用文档来管道:https://docs.python.org/2/library/subprocess.html#subprocess.check_call
一个快速的实验证明这是有效的:转到你的bash终端执行
echo "echo test" | /bin/bash
结果呢?
test
不
echo test