在C#中调用python脚本,并使用python第三方arcpy模块

前言
1、C#中调用python脚本,一是通过ironpython直接运行python脚本,二是通过调用Process类启动电脑上的python.exe,运行python脚本。
前者在使用第三方arcpy模块式,会提示错误:No Module Named arcpy,网上的解决方案是在python脚本中通过sys.appendpath添加arpy路径,但是又会提示新的错误:No Module Named arcgisscripting……未解决,所以本文采用第二种方式
以arcgis merge功能为例
(1)新建c#窗体应用

(2)窗体界面如图:

(3)button2点击事件代码:
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Multiselect = true;
fileDialog.Title = “输入数据集”;
fileDialog.Filter = “shapefiles(*.shp)|*.shp|All files(*.*)|*.*”;//过滤文件类型
if (fileDialog.ShowDialog() == DialogResult.OK)
{
string[] names = fileDialog.FileNames;
int flag = 0;
foreach (string file in names)
{
MessageBox.Show(“已选择文件:” + file, “选择文件提示”, MessageBoxButtons.OK, MessageBoxIcon.Information);
if(flag==0)
textBox5.Text=”F:\\data\\output\\merge.shp”;//设置默认存储路径
textBox3.AppendText(file+”\n”);
}
}
}
(4)button1点击事件代码
private void button1_Click(object sender, EventArgs e)
{
string arg1_ = textBox3.Text;//获取参数arg1[](待合并图层集合)
string[] arg1 = arg1_.Split(‘\r’, ‘\n’);
string arg2 = textBox5.Text;//arg2(输出图层)
List<string> listArr = arg1.ToList();
listArr.Add(arg2);
string[] strArr = listArr.ToArray(); //参数列表,需要传递的参数
string sArguments = @”merge.py”;//这里是python的文件名字
RunPythonScript(sArguments, “-u”, strArr);//运行脚本文件
}
public static void RunPythonScript(string sArgName, string args = “”,params string[] teps)
{
Process p = new Process();
string path = “merge.py”;// 待处理python文件的路径
string sArguments = path;
foreach (string sigstr in teps)//添加参数
{
sArguments += ” ” + sigstr;//传递参数
}
//下面为启动一个进程来执行脚本文件设置参数
p.StartInfo.FileName = @”C:\Python27\ArcGIS10.2\python.exe”; //注意路径
p.StartInfo.Arguments = sArguments;//这样参数就是merge.py 路径1 路径2 路径3….
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();//启动进程
}
(5)merge.py
import arcpy
from arcpy import env
import sys
# 这里只取了前两个输入数据集作为合并对象
arcpy.Merge_management([sys.argv[1], sys.argv[2]], sys.argv[len(sys.argv)-1])
注意:merge,py放在WindowsFormsApplication1\bin\Debug目录下
(6)运行结果

You may also like...