python - 如何再次打开关闭的标准输入子进程?
问题描述
我有一个代码将在 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
它运行第一个命令,但第二次给出错误(关闭标准输入后)
我到处搜索但找不到与此相关的任何内容
解决方案
推荐阅读
- python - 如何在 PyQt5 中横向打印?
- c - GCC 未定义的参考。找不到图书馆
- java - 使用请求和响应的字符串调用 SOAP Web 服务的最简单方法是什么?
- python-2.7 - 如何修复 urlopen 错误 [SSL: CERTIFICATE_VERIFY_FAILED] 证书验证失败 (_ssl.c:590)> 错误
- python - 在字符串 python 中搜索列表的特定项目
- python - 创建一个新列,它是所有前面的列的串联
- python - Scikit learn的AttributeError:'LabelEncoder'对象没有属性'classes_'?
- c# - C# SOAP 服务 - 删除方法节点并在soapheader 节点中有标头
- java - LWJGL glfwInit 因验证错误而失败
- excel - 创建附有会议邀请的电子邮件