200字范文,内容丰富有趣,生活中的好帮手!
200字范文 > python调用exe程序 传入参数_关于使用c#调用python脚本文件 脚本文件需要传递参数...

python调用exe程序 传入参数_关于使用c#调用python脚本文件 脚本文件需要传递参数...

时间:2021-04-15 16:41:01

相关推荐

python调用exe程序 传入参数_关于使用c#调用python脚本文件 脚本文件需要传递参数...

最近工作中需要干这个事,网上搜了搜资料,改了改,基本是这样

建立一个控制台应用程序:

比如 加入我在命令行直接调用python脚本,命令为

y安装python后,添加环境变量,path下面,加入路径。

feng.py是需要执行的python脚本,command是其命令,-f 是参数 xx.os是需要操作对应的文件

static void Main(string[] args)

{

string[] strArr;//参数列表,需要传递的参数,这里只需要传递command -f xx.os 注意路径的正确

string sArguments = @"feng.py";//这里是python的文件名字

RunPythonScript(sArguments, "-u", strArr);//运行脚本文件

}

public static void RunPythonScript(string sArgName, string args = "",params string[] teps)

{

Process p = new Process();

string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + sArgName;// 获得python文件的绝对路径,如果是绝对路径,尽量保证 //同一级目录名称没有空格 比如 "C://xx//ni hao//; //这里的ni hao之间有空格,会引发错误,得不到相应结果。

string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + sArgName;// 获得python文件的相对路径

string sArguments = path; if (tep.Length > 0)

{

foreach (string sigstr in teps)

{

sArguments += " " + sigstr;//传递参数

}

}

//下面为启动一个进程来执行脚本文件设置参数

p.StartInfo.FileName = @"python26.exe"; //注意路径,相对路径在Debug目录下,这里是安装python26.exe

p.StartInfo.Arguments = sArguments;//这样sArguments就变成了feng.py command -f xx.os

p.StartInfo.UseShellExecute = false;

p.StartInfo.RedirectStandardOutput = true;

p.StartInfo.RedirectStandardInput = true;

p.StartInfo.RedirectStandardError = true;

p.StartInfo.CreateNoWindow = true;

p.Start();//启动进程

p.BeginOutputReadLine(); p.OutputDataReceived += new DataReceivedEventHandler(p_OutputDataReceived);

Console.ReadLine();

p.WaitForExit(); } //输出打印的信息

static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)

{

if (!string.IsNullOrEmpty(e.Data))

{

AppendText(e.Data + Environment.NewLine);

}

}

public delegate void AppendTextCallback(string text);

public static void AppendText(string text)

{

Console.WriteLine(text);

}

}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。