【发布时间】:2021-06-20 03:43:09
【问题描述】:
我正在制作一个终端命令行界面程序,作为一个更大项目的一部分。我希望用户能够运行任意命令(如在 cmd 中)。问题是当我使用subprocess 启动python 进程时,python 不会向stdout 写入任何内容。我什至不确定它是否读到了我在stdin 中写的内容。这是我的代码:
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)))
当我将"python" 更改为"myexe.exe" 时,上面的代码有效,其中myexe.exe 是我用MinGW 编译的C++ 编写的hello world 程序。为什么会这样? This 是完整代码,但上面的示例显示了我的问题。当我将"python" 更改为"cmd" 时,它也可以正常工作。
PS:当我在命令提示符下运行 python 时,它给了我:
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.
>>>
这意味着应该有东西写到stdout。
【问题讨论】:
-
你确定 REPL 输出是标准输出吗?
-
@OneCricketeer 好吧,我假设 python 进程应该写入标准输出,因为当我从 cmd 运行它时,它会将内容写入屏幕。是这个意思吗?
-
@OneCricketeer 我检查了 stderr 它也是空的
-
所以,你永远不会为 REPL 发送“输入键”/换行符来实际执行任何操作,那么为什么不直接使用
eval()而不是子shell? -
另一方面,将 exit()\n 发送到标准输入 - 而不是 hello world - 并没有关闭执行,所以这可能也不起作用。
标签: python python-3.x subprocess pipe