如何再次打开关闭的stdin子进程?

时间:2018-12-24 08:07:31

标签: python python-3.x windows error-handling subprocess

我有一个将在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

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

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

0 个答案:

没有答案