ArcEngine调用cmd执行python



介绍

经常使用ArcGIS的小伙伴估计经常需要用到ArcToolBox,这个工具箱提供了丰富的工具为我们进行数据处理等操作,但是我们在程序中如何使用这些工具呢?

Esri提供了GP工具为我们执行这些操作,但是使用过GP工具的同学都知道这个接口并不是特别的好用,而Esri也主推大家使用Python去处理我们的数据,下面介绍如何调用cmd执行我们的python.

如果你不知道python如何写,Esri的官网提供了Arcpy文档,或者直接找到地理处理工具(中文),每一个实际的工具都包括Python窗口独立脚本两种示例代码~

也可以直接在打开的工具中直接索引到本地的帮助文档

这里写图片描述


这里我们的参数以字符串的形式传递,由于不知道参数的个数,所以我们的参数使用了params关键字,在python脚本中使用arcpy.GetParameterAsText(index)就可以根据索引取到每个传递进来的参数了!

        /// <summary>
        /// 调用python执行GP(python的执行代码可以在Esri的官方的帮助文档上找到,每一个GP都有)
        /// </summary>
        /// <param name="filePath">.py文件的全路径</param>
        /// <param name="paramList">参数列表</param>
        /// <returns></returns>
        public static bool RunPython(string filePath, params string[] paramList)
        {
            try
            {
                string paramStr = "/c " + filePath;//cmd中执行的字符串
                if (paramList.Length > 0)
                {
                    foreach (var item in paramList)
                    {
                        paramStr += " " + item;
                    }
                }

                ProcessStartInfo pProcessInfo = new ProcessStartInfo("cmd", paramStr);
                pProcessInfo.RedirectStandardOutput = true;
                pProcessInfo.RedirectStandardError = true;
                pProcessInfo.RedirectStandardInput = true;
                pProcessInfo.UseShellExecute = false;
                pProcessInfo.CreateNoWindow = true;

                string output = string.Empty;
                string outMsg = string.Empty;

                using (Process p = new Process())
                {
                    p.StartInfo = pProcessInfo;

                    p.Start();

                    output = p.StandardError.ReadToEnd();
                    outMsg = p.StandardOutput.ReadToEnd();
                }
                GC.Collect();
                GC.WaitForPendingFinalizers();

                return (output.Length == 0 && outMsg.Length == 0);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

转载自:https://blog.csdn.net/sx341125/article/details/52806183

You may also like...