关于使用c#调用python脚本文件,脚本文件需要传递参数

来源:互联网 发布:阿尔法营创意编程 编辑:程序博客网 时间:2024/06/02 00:00

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

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

比如 加入我在命令行直接调用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);           }}
0 0
原创粉丝点击