Write to stdin of a running process in windows

2019-04-28 04:43发布

I want to write data to the existing process's STDIN from external processes in windows , and found similar question for linux :

How to write data to existing process's STDIN from external process?

How do you stream data into the STDIN of a program from different local/remote processes in Python?

https://serverfault.com/questions/443297/write-to-stdin-of-a-running-process-using-pipe

and etc, but now i want to know how can i do that in windows ?
I'm try with this code but i got error !
also i try for running program and send stdin to that with this cod but again error !

In CMD :

type my_input_string | app.exe -start
my_input_string | app.exe -start
app.exe -start < pas.txt

In python :

    p = subprocess.Popen('"C:\app.exe" -start',
 stdin=subprocess.PIPE, universal_newlines=True, shell=True)    
    grep_stdout = p.communicate(input='my_input_string')[0]

Error is this :

ReadConsole() failed: The handle is invalid.

And in C# :

        try
        {
            var startInfo = new ProcessStartInfo();
            startInfo.RedirectStandardInput = true;
            startInfo.FileName = textBox1.Text;
            startInfo.Arguments = textBox2.Text;
            startInfo.UseShellExecute = false;

            var process = new Process();
            process.StartInfo = startInfo;
            process.Start();
            Thread.Sleep(1000);
            var streamWriter = process.StandardInput;
            streamWriter.WriteLine("1");
        }
        catch (Exception ex)
        { 
                textBox4.Text = ex.Message+"\r\n"+ex.Source;
        }

enter image description here In C# with that code App.exe (command line application whis start with new process) crashed ! but in C# application i dont have any exception !
and i think that is for UseShellExecute = false;
Also when i use from C# and if don't run app in background I can find process and use from sendkeys to send my_input_string to that but this is not good idea because user see command line when use from GUI !

how can i send stdin without error with only CMD or create script in python or C# !
Have any idea ???

Kind regards.

1条回答
对你真心纯属浪费
2楼-- · 2019-04-28 05:17

If you're launching, and then supplying the input from c#, you can do something like this:

var startInfo = new ProcessStartInfo("path/to/executable");
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;

var process = new Process();
process.StartInfo = startInfo;
process.Start();

var streamWriter = process.StandardInput;
streamWriter.WriteLine("I'm supplying input!");

If you need to write to the standard input of an application already running, I doubt that is easy to do with .net classes, as the Process class will not give you the StandardInput (it will instead throw an InvalidOperationException)

Edit: Added parameter to ProcessStartInfo()

查看更多
登录 后发表回答