如何使用Python打开bash会话并与之保持通信? [英] How to open a bash session with Python and keep communicating with it?

查看:44
本文介绍了如何使用Python打开bash会话并与之保持通信?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在python中打开bash会话并保持与之交互,就好像它是一个终端一样.这是我到目前为止的内容:

I would like to open a bash session in python and keep interacting with it as if it was a terminal. This is what I have so far:

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期间,我得到了这个输出,但是失败了

However, during git clone I get this output, and it fails

Cloning into 'crapi'...
EOF

推荐答案

好的,完整的免责声明,python可能是我的第一语言,但肯定不是我的最佳选择

Alright, full disclaimer, python may have been my first language, but sure ain't my best

这应该使您入门:

self.execute("/bin/bash")#spawn a bash session

在那之后,您可以将命令通过管道传输到bash.我不确定您要实现的目标,但是您可以在此处使用文档进行管道传输: https://docs.python.org/2/library/subprocess.html#subprocess.check_call

After that, you can pipe commands to bash. I'm not fully sure what you're trying to achieve, but you can pipe using the docs here: https://docs.python.org/2/library/subprocess.html#subprocess.check_call

一个快速的实验来证明这是可行的:转到您的bash终端执行

A quick experiment to prove this works: Go to your bash terminal Execute

echo "echo test" | /bin/bash

结果如何?

test

echo test

这篇关于如何使用Python打开bash会话并与之保持通信?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆