[英]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我创建了一个“hello.py”文件并将其放在与我的 c#.exe 相同的目录中
and I run this on the command prompt via c# and this is my progress so far我通过 c# 在命令提示符下运行它,这是我到目前为止的进展
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但是当我运行它时,output 出来了
Microsoft Windows [Version 10.0.19041.685]微软 Windows [版本 10.0.19041.685]
(c) 2020 Microsoft Corporation. (c) 2020 年微软公司。 All rights reserved.版权所有。C:\... \Debug>python hello.py C:\... \Debug>python hello.py
hello world你好世界C:\... \Debug> C:\...\调试>
But i specifically need the "hello world" part但我特别需要“hello world”部分
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#?还有什么方法可以通过 c# 输入到 cmd 中?
for example if i made a calc.py which inputs 2 numbers and then prints their sum?例如,如果我制作了一个输入 2 个数字然后打印它们的总和的 calc.py?
NOTE笔记
My aim is not to integrate python and c#, I just took.py as an example我的目的不是整合python和c#,我只是以.py为例
so please provide a solution that is applicable to.exe or any command prompt executable所以请提供适用于.exe或任何命令提示符可执行文件的解决方案
Try setting尝试设置
cmd.StartInfo.Arguments = "/c python hello.py"
instead of passing your command using StandardInput.而不是使用 StandardInput 传递您的命令。
This is equivalent to typing这相当于输入
cmd /c python hello.py
at a command prompt, instead of typing:在命令提示符下,而不是键入:
cmd
followed by其次是
python hello.py
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.