Skip to main content
 首页 » 编程设计

python之如何用 Python 打开 bash session 并保持通信

2025年05月04日10cloudgamer

我想在 python 中打开一个 bash session 并保持与它交互,就好像它是一个终端一样。这是我目前所拥有的:

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