1

我有一个用 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 脚本中实现了自动化。

4

1 回答 1

0

我找到了解决这个问题的方法。我的主要目的是使用程序将输入传递给控制台应用程序。由于我无法捕获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)
于 2019-09-27T09:33:20.530 回答