gpt4 book ai didi

c# - 如何使用 subprocess.Popen() 通过 python 脚本捕获用 C# 编写的控制台应用程序的标准输入,其中包含 Console.ReadKey()

转载 作者:太空宇宙 更新时间:2023-11-03 20:23:13 24 4
gpt4 key购买 nike

我有一个用 C# 编写的控制台应用程序。我正在尝试使用 python 脚本自动执行它。控制台应用程序使用 Console.ReadKey() 而不是 Console.ReadLine()Console.Read()。当我尝试使用 python subprocess.Popen()

时,出现无效操作异常

根据微软文档

"The In property is redirected from some stream other than the console."

如果我捕获应用程序的 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 脚本中实现了自动化。

最佳答案

我找到了解决这个问题的方法。我的主要目的是使用程序将输入传递到控制台应用程序。由于我无法捕获 stdin 并传递输入,因此我想到了模仿按键。我为此使用了“pyautogui”。

import subprocess
from subprocess import run,call,PIPE,Popen
import time
from pyautogui import press

with Popen(["CommandProgram.exe"],stdout=PIPE,encoding = 'UTF-8') as process:
print('Writing the command')
time.sleep(2)
#out,err = process.communicate('help')
out = process.stdout.readline()
process.stdout.flush()
press('h')
press('e')
press('l')
press('p')
press('enter')
for line in process.stdout :
print(line)
process.stdout.flush()
press('r')
press('u')
press('n')
press('enter')
for line in process.stdout :
print(line)

关于c# - 如何使用 subprocess.Popen() 通过 python 脚本捕获用 C# 编写的控制台应用程序的标准输入,其中包含 Console.ReadKey(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58026041/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com