I am making a terminal command line interface program as part of a bigger project. I want the user to be able to run arbitrary commands (like in cmd). The problem is that when I start a python
process using subprocess
, python doesn't write anything to stdout
. I am not even sure if it reads what I wrote in stdin
. This is my code:
from os import pipe, read, write
from subprocess import Popen
from time import sleep
# Create the stdin/stdout pipes
out_read_pipe_fd, out_write_pipe_fd = pipe()
in_read_pipe_fd, in_write_pipe_fd = pipe()
# Start the process
proc = Popen("python", stdin=in_read_pipe_fd, stdout=out_write_pipe_fd,
close_fds=True, shell=True)
# Make sure the process started
sleep(2)
# Write stuff to stdin
write(in_write_pipe_fd, b"print(\"hello world\")\n")
# Read all of the data written to stdout 1 byte at a time
print("Reading:")
while True:
print(repr(read(out_read_pipe_fd, 1)))
The code above works when I change "python"
to "myexe.exe"
where myexe.exe
is my hello world program written in C++ compiled by MinGW. Why does this happen? This is the full code but the above example shows my problem. It also works correctly when I change "python"
to "cmd"
.
PS: when I run python
from the command prompt it gives me:
Python 3.7.9 (tags/v3.7.9:13c94747c7, Aug 17 2020, 18:58:18) [MSC v.1900 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
That means that there should be stuff written to stdout
.