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

标签 c# python automation subprocess console.readkey

我有一个用 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/

相关文章:

python - 如何在 SqlAlchemy 中进行不带 JOIN 的嵌套 SELECT?

python - 如何解决AttributeError : SMTP_SSL instance has no attribute '__exit__' in Python?

java - 如何检查 Selenium 中面包屑的顺序

python - 使用 Python 与其他程序交互

c# - 无法调用具有很长参数列表的 WCF 服务

python - 使用 shutil 在 python 中移动文件

c# - 如何从Excel工作表中读取第3行的数据并转换为数据表

automation - 自动化 Google 外卖下载

c# - Parallel.Foreach - NULL 任务

c# - Request.Browser.IsMobileDevice 不适用于 iPadAir2 和 iOS 13.0.1