Home > other >  How to embed/spawn an interactive shell from inside a Python program
How to embed/spawn an interactive shell from inside a Python program

Time:02-02

I have a Python 3 CLI application from which I want to drop into or spawn an interactive bash shell (after I’ve set some custom environment vars).

What is the best way to embed or spawn an interactive bash shell in Python?

More details

The whole procedure can be described in the following 6 steps:

  1. The user starts my CLI application in a Terminal session. (It should work regardless whether the app runs in iTerm or Xterm or the like, but the underlying system is Unix-ish.)

  2. Then the application gathers some information from the user via prompts (so the application uses stdin and stdout).

  3. Then it should spawn a bash shell prompt. This bash is suppose to:

    • run in the same terminal session as my app and
    • use an environment with some custom environment vars set by my application beforehand.
  4. The user executes some commands in the bash shell (using the same stdin and stout from my app before).

  5. The user exists the bash shell via Ctrl-d or exit.

  6. The bash shell closes and my Python app takes over again in the same terminal session. It does some post [proecssing and the finishes.

The part I am asking about is step 3 (Spawn the bash shell).

What I've tried to spawn a bash

  1. I tried using the code module in the Standard Library, but this only allows me to start a Python shell not a bash shell.

  2. I used the sh package:

     from sh import bash
     bash('-i')
    

    This doesn't work either.

CodePudding user response:

Just:

import subprocess
subprocess.run(['bash', '-li'])

You can pass your custom environment via env function parameter, and anything more with --rcfile bash argument.

CodePudding user response:

Does this solve your problem:

import os
os.system("x-terminal-emulator -e /bin/bash")
  •  Tags:  
  • Related