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);
}
}
總結
以上是生活随笔為你收集整理的python调用exe程序 传入参数_关于使用c#调用python脚本文件,脚本文件需要传递参数...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python类和对象详解_Python公
- 下一篇: anaconda安装tensorflow