C#调用其他运行程序——以python为例

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/L_J_Kin/article/details/102764711

1.NET上的Python工具:IronPython

IronPython是一种在.NET和Mono上实现的Python语言,包含一套python的核心类,但是不包含第三方类,如果在python文件中采用import等方式加载第三方类均会失败。

2. 通过C#创建进程代码

添加一个执行Python的函数RunPythonScript。

public static void RunPythonScript(string sArgName, string args = "", params string[] teps)
{            
	Process p = new Process();	
	string sArguments = sArgName;
	foreach (string sigstr in teps)//添加参数
	{
		sArguments += " " + sigstr;//传递参数
	}
	sArguments += " " + args;
		
	p.StartInfo.FileName = @"C:\Python27\ArcGIS10.2\python.exe"; 
	p.StartInfo.Arguments = sArguments;
	Console.WriteLine(sArguments);
	p.StartInfo.UseShellExecute = false;
	p.StartInfo.RedirectStandardOutput = true;
	p.StartInfo.RedirectStandardInput = true;
	p.StartInfo.RedirectStandardError = true;
	p.StartInfo.CreateNoWindow = true;
	p.Start();//启动进程
	p.BeginOutputReadLine();
	Console.ReadLine();
	p.WaitForExit();
}

调用RunPythonScript

private void runPython(object sender, EventArgs e)
{
	string[] strArr = new string[paranum];
	//paranum: Python函数中参数的个数
	//strArr: Python函数的参数
	string sArguments = @"pythonfile/pythonfile.py";
	//sArguments: Python函数的路径(可为相对路径)
	RunPythonScript(sArguments, "-u", strArr);
}

未完待续。

猜你喜欢

转载自blog.csdn.net/L_J_Kin/article/details/102764711