0

I tried to run a system shell in Python subprocess module:

p = subprocess.Popen("/bin/bash", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
p.wait()
print(p.communicate())

However, it printed (b'', b'')
I tried other shells too, but they all failed to work. (Zsh, Sh, and FiSH)
How can I get the output? Thanks in advance!

2
  • 2
    What is your expected output? Commented May 12, 2022 at 7:38
  • I think it should print the prompt, like "~/directory $" Commented May 12, 2022 at 8:46

1 Answer 1

2

It works for me as you would expect I guess.

(base) tzane:~/python_test$ python test_1.py
whereis ls
exit
(b'ls: /bin/ls /usr/share/man/man1/ls.1.gz\n', b'')
(base) tzane:~/python_test$

You are not getting any output if you are not telling bash to output anything. Calling .wait() with pipes can cause deadlocks so I would do something like this instead

import subprocess

p = subprocess.Popen("/bin/bash", stdout=subprocess.PIPE, stderr=subprocess.PIPE)
try:
    print(p.communicate(timeout=30))
except TimeoutExpired:
    p.kill()
    print(p.commnunicate())

as suggested in the documentation or just use subprocess.run if you don't have to interact with the subprocess and you just want to catch the output.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. So I have to put something in stdin before reading the stdout, right?
@AndyZhang In the case of bash, yes, because bash doesn't output anything unless you tell it to. If you were to run a subprocess command like this p = subprocess.Popen("echo monty", shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE) you would get (b'monty\n', b'') without having to write anything to stdin.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.