首页 > 解决方案 > 如何再次打开关闭的标准输入子进程?

问题描述

我有一个代码将在 Python 中运行 CMD 它会要求输入将其发送到 CMD 并等待输出(在同一过程中)我尝试了以下代码:

import subprocess
p = subprocess.Popen('cmd.exe', stdin=subprocess.PIPE,
             stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdin_copy = os.fdopen(os.dup(sys.stdin.fileno()), sys.stdin.mode)
while True:
    cmd = input("$")
    p.stdin.write(bytes(str(cmd + "\n").encode("utf-8"))
    p.stdin.close()
    print(p.stdout.read().decode("utf-8"))

输出:

$cd H:\\
Microsoft Windows [Version 10.0.17763.195]
(c) 2018 Microsoft Corporation. All rights reserved.

H:\PythonProjects\DatabaseTest>cd H:\\

H:\>
$cd H:\\MyPython\\
Traceback (most recent call last):
  File "H:/PythonProjects/DatabaseTest/c.py", line 6, in <module>
    p.stdin.write(bytes(str(cmd + "\n").encode("utf-8")))
ValueError: write to closed file

Process finished with exit code 1

它运行第一个命令,但第二次给出错误(关闭标准输入后)

我到处搜索但找不到与此相关的任何内容

标签: pythonpython-3.xwindowserror-handlingsubprocess

解决方案


推荐阅读