1

I have a console application that is written in C#. I am trying to automate its execution using python script. The console application uses Console.ReadKey() instead of Console.ReadLine() or Console.Read(). I am getting invalid operation exception when I try to use python subprocess.Popen()

According to Microsoft documentation

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

If I capture the stdin of the app, it will detect that stdin has been redirected from console input stream and throw an Invalid operation exception.

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)

My script is as folllows

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)

I am trying to find a workaround for this problem. I think it is possible because, so many console application gets automated in python scripts.

orde
  • 5,233
  • 6
  • 31
  • 33
Aditya Nadig
  • 203
  • 3
  • 12

1 Answers1

0

I found hack for this problem. My main purpose was to pass the input to the console application using a program. Since i cannot capture the stdin and pass the input, i thought of mimicking key press. I used 'pyautogui' for this.

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)
Aditya Nadig
  • 203
  • 3
  • 12