5

I'd like to know if it's possible to run a bash script inside a Python Script and get the bash script output "live" (not after the Python script ran the bash script, I know how to do that).

You'd probably ask me why I want to use a Python Script : actually I'd like build a nice CLI interface and I'm using Inquirer to do that. This interface allows the user to perform task that are actually performed using bash scripts. That's why I'm not using a bash script that executes other scripts.

4
  • Share some code about what you have done till now Commented Sep 16, 2019 at 10:43
  • 1
    You will have to use the subprocess.Popen class and capture the output files (stderr and stdout). Commented Sep 16, 2019 at 10:47
  • So you want to capture the input data from the terminal "live"? Commented Sep 16, 2019 at 11:06
  • I wanted to capture the script output and print it live, I didn't want to wait until the end of bash script execution. milanbalazs' answer is accurate and solves my problem ! Commented Sep 16, 2019 at 11:59

1 Answer 1

6

You can use the following implementation to get the STDOUT of shell script in real-time.

Code:

cmd="whoami"
p = subprocess.Popen(cmd, stdout=subprocess.PIPE, bufsize=1)
for line in iter(p.stdout.readline, b''):
    print(line)
p.stdout.close()
p.wait()

Output:

>>> python3 test.py 
b'milanbalazs\n'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, that was exactly what I wanted to do !

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.