How to open a bash session with Python and keep co

2019-07-18 09:52发布

问题:

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")

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

Cloning into 'crapi'...
EOF

回答1:

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

This should get you started:

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

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

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

echo "echo test" | /bin/bash

and the result?

test

NOT

echo test