C#调用Arcpy+Python脚本

31 篇文章 6 订阅
26 篇文章 8 订阅

C#调用Arcpy+Python脚本

利用c#+Winform+cmd搭建界面和传参,利用Arcpy+Python脚本执行任务,监听脚本的返回值判断程序是否执行完毕!注意事项:

  1. 脚本必须正常执行,在cmd下面也能正常执行;
  2. 传参的参数间要用空格。

例子:

  • ArcpyForm.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
using System.Threading;
using System.Configuration;

namespace exe
{
    public partial class ArcpyForm : Form
    {
        delegate void SetTextHander(string recvStr);//带参数
        private void SetText(string recvStr)
        {
            if (richTextBox1.InvokeRequired)//判断是否是线程在访问该控件
            {
                SetTextHander set = new SetTextHander(SetText);//委托的方法参数应和SetText一致
                richTextBox1.Invoke(set, recvStr); //委托自身,递归委托,直到不是以invoke方式去访问控件
            }
            else
            {
                richTextBox1.SelectionColor = Color.Red;
                richTextBox1.AppendText(Thread.CurrentThread.ManagedThreadId + "回调结束------------" + DateTime.Now.Second.ToString() + ":" + DateTime.Now.Millisecond.ToString() + "------------------------------------------\r\n");
                richTextBox1.SelectionColor = Color.Blue;
                richTextBox1.AppendText(recvStr + "\r\n");
            }


        }

        public ArcpyForm()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 不带参数执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlSBtn_Start_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();
            string pythonexe = ConfigurationManager.AppSettings["pythonexe"].ToString();
            string python = ConfigurationManager.AppSettings["python"].ToString();
            string pythonDir = ConfigurationManager.AppSettings["pythonDir"].ToString();

            string pythonScriptPath = pythonDir; //AppDomain.CurrentDomain.BaseDirectory;//python脚本所在的目录
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = pythonexe; //@"C:\SoftWare\ArcGis\ArcGIS10.1\python.exe";//执行python.exe
            //执行python脚本的命令
            start.Arguments = python;// pythonScriptPath + "pythonGUI.py";
            //设置运行python脚本的初始目录 这里注意:如果你的python脚本有文件操作,必须设置初始目录
            start.WorkingDirectory = pythonScriptPath;
            start.UseShellExecute = false;
            start.CreateNoWindow = true;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;
            using (Process process = Process.Start(start))
            {
                // 异步获取命令行内容
                process.BeginOutputReadLine();
                // 为异步获取订阅事件
                process.OutputDataReceived += new DataReceivedEventHandler((sender1, e1) =>
                {
                    SetText(e1.Data);
                });
            }

        }

        /// <summary>
        /// 带参数执行
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void tlSBtn_Start_Argv_Click(object sender, EventArgs e)
        {
            richTextBox1.Clear();

            string pythonexe = ConfigurationManager.AppSettings["pythonexe"].ToString();
            string python = ConfigurationManager.AppSettings["python"].ToString();
            string pythonDir = ConfigurationManager.AppSettings["pythonDir"].ToString();
            string parameters = ConfigurationManager.AppSettings["parameters"].ToString();

            string pythonScriptPath = pythonDir; //AppDomain.CurrentDomain.BaseDirectory;//python脚本所在的目录
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = pythonexe; //@"C:\SoftWare\ArcGis\ArcGIS10.1\python.exe";//执行python.exe
            //执行python脚本的命令
            start.Arguments = python + " " + parameters;// pythonScriptPath + "pythonGUI.py";
            //设置运行python脚本的初始目录 这里注意:如果你的python脚本有文件操作,必须设置初始目录
            start.WorkingDirectory = pythonScriptPath;
            start.UseShellExecute = false;
            start.CreateNoWindow = true;
            start.RedirectStandardOutput = true;
            start.RedirectStandardError = true;
            using (Process process = Process.Start(start))
            {
                // 异步获取命令行内容
                process.BeginOutputReadLine();
                // 为异步获取订阅事件
                process.OutputDataReceived += new DataReceivedEventHandler((sender1, e1) =>
                {
                    SetText(e1.Data);
                });
            }

        }

    }
}
  • App.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <!--python.exe-->
    <add key="pythonexe" value="C:\SoftWare\ArcGis\ArcGIS10.1\python.exe"/>
    <!--*.py-->
    <add key="python" value="F:\Project\exe\exe\bin\Debug\pythonGUIArgv.py"/>
    <!--*.py目录-->
    <add key="pythonDir" value="F:\Project\exe\exe\bin\Debug" />

    <!--python参数,参数之间留一个空格-->
    <add key="parameters" value="C:\Users\Administrator\Desktop\y\33 C:\Users\Administrator\Desktop\y\ee\1.mdb" />
    
  </appSettings>
  <system.windows.forms jitDebugging="true" />
</configuration>
  • pythonGUI.py 脚本
# coding=utf-8
import arcpy
import string
import sys
try:
    workspace =r'C:\Users\Administrator\Desktop\y\33'
    outdb1 = r"C:\Users\Administrator\Desktop\y\ee\1.mdb"
    arcpy.env.workspace = workspace
    files = arcpy.ListFiles("*.*db")
    arcpy.env.workspace = outdb1
    fcs = arcpy.ListFeatureClasses()
    fcs = fcs + arcpy.ListTables()
    dss = arcpy.ListDatasets()
    for File in files:
        print File
        for fc in fcs:
            arcpy.Append_management(workspace + "\\" + File + "\\" + fc, outdb1 + "\\" + fc)
        for ds in dss:
            fcs1 = arcpy.ListFeatureClasses(feature_dataset=ds)
            for fc1 in fcs1:
                print fc1
                arcpy.Append_management(workspace + "\\" + File + "\\" + ds + "\\" + fc1, outdb1 + "\\" + ds + "\\"+fc1)
except arcpy.ExecuteError:
    print arcpy.GetMessages()
  • 效果图

在这里插入图片描述

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梅里雪山GIS

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值