我有一个用 C# 编写的控制台应用程序。我正在尝试使用 python 脚本自动执行它。控制台应用程序使用Console.ReadKey()
代替Console.ReadLine()
or Console.Read()
。尝试使用 python 时出现无效操作异常subprocess.Popen()
根据微软文档
“In 属性是从控制台以外的某个流重定向的。”
如果我捕获stdin
应用程序的 ,它将检测到stdin
已从控制台输入流重定向并抛出无效操作异常。
Unhandled Exception: System.InvalidOperationException: Cannot read keys
when either application does not have a console or when console input has
been redirected
from a file. Try Console.Read.
at System.Console.ReadKey(Boolean intercept)
我的脚本如下
import subprocess
from subprocess import run,call,PIPE,Popen
import time
with Popen(['ConsoleProgram.exe'],stdout=PIPE,stdin=PIPE,encoding ='UTF-8') as process:
print('Writing the command')
time.sleep(5)
out,err = process.communicate('help')
if(err != None):
print('Command execution failed')
else:
print(out)
我正在尝试找到解决此问题的方法。我认为这是可能的,因为有很多控制台应用程序在 python 脚本中实现了自动化。