简体   繁体   中英

How to operate command prompt using c#?

I've created a "hello.py" file and placed it in the same directory as my c#.exe
and I run this on the command prompt via c# and this is my progress so far

using System.Diagnostics;
using System;
namespace c_hash_testing 
{
    class Primary
    {
        static void run()
        {
            Process cmd = new Process();
            cmd.StartInfo.FileName = "cmd.exe";
            cmd.StartInfo.RedirectStandardInput = true;
            cmd.StartInfo.RedirectStandardOutput = true;
            cmd.StartInfo.CreateNoWindow = true;
            cmd.StartInfo.UseShellExecute = false;
            cmd.Start();

            cmd.StandardInput.WriteLine("python hello.py");
            cmd.StandardInput.Flush();
            cmd.StandardInput.Close();
            cmd.WaitForExit();
            Console.WriteLine(cmd.StandardOutput.ReadToEnd());
        }
        static void Main(string[] args) 
        {
            run();
            Console.ReadKey();
        }

    }
}

but when i run it the output comes out to be

Microsoft Windows [Version 10.0.19041.685]
(c) 2020 Microsoft Corporation. All rights reserved.

C:\... \Debug>python hello.py
hello world

C:\... \Debug>

But i specifically need the "hello world" part
so is there any way to read only the executed part because I don't want to sort the string out every time I run something else,

also is there any possible way that I could input into the cmd via c#?
for example if i made a calc.py which inputs 2 numbers and then prints their sum?

NOTE
My aim is not to integrate python and c#, I just took.py as an example
so please provide a solution that is applicable to.exe or any command prompt executable

Try setting

cmd.StartInfo.Arguments = "/c python hello.py"

instead of passing your command using StandardInput.

This is equivalent to typing

cmd /c python hello.py

at a command prompt, instead of typing:

cmd

followed by

python hello.py

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM