惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Y
Y Combinator Blog
有赞技术团队
有赞技术团队
J
Java Code Geeks
H
Hackread – Cybersecurity News, Data Breaches, AI and More
美团技术团队
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Hugging Face - Blog
Hugging Face - Blog
人人都是产品经理
人人都是产品经理
酷 壳 – CoolShell
酷 壳 – CoolShell
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
C
Check Point Blog
博客园 - 【当耐特】
The GitHub Blog
The GitHub Blog
Recent Announcements
Recent Announcements
The Cloudflare Blog
Microsoft Azure Blog
Microsoft Azure Blog
腾讯CDC
Vercel News
Vercel News
IT之家
IT之家
MyScale Blog
MyScale Blog
博客园_首页
Martin Fowler
Martin Fowler
WordPress大学
WordPress大学
罗磊的独立博客

博客园 - 云梦鸿

Winform界面显示的“语言”切换 Linux使用笔记 QT 练习笔记 QT 读写配置文件(*.INI) ubuntu 配置网口静态IP C++ 读写文件 C#编写Windows服务 C#代码计算农历(日期、节气、节日) 中标麒麟,使用笔记 关于无密码访问 Windows7/10 的远程桌面/共享 颜色转换:HSB颜色 与 RGB颜色 QT 信号(槽)绑定的使用_connect QT 给控件(Label)设置显示图片 QT 打包Windows应用程序(*.exe) C#监控U盘插拔 C# AnimateWindow 设置窗体动画 C# GetWindowRect 获取窗体在屏幕中的位置信息 C# 创建音频WAVE文件头信息(*.wav) VS2019错误:CS8370 的处理方法
C#程序执行Python脚本
云梦鸿 · 2021-02-07 · via 博客园 - 云梦鸿

方法介绍:

     通过调用“Python.exe”程序,执行脚本文件。所以,本方式要求电脑上已经安装了Python,拥有程序Python.exe程序。

现在,有如下py脚本:Add.py

import sys

def Add(a,b):
    return a+b

if __name__=='__main__':
    X = int(sys.argv[1])
    Y = int(sys.argv[2])
    ret = Add(X,Y)
    print(ret)

然后,设计C#窗口程序,界面如下:

后端C#代码如下(只截取关键代码):

        private void button1_Click(object sender, EventArgs e)
        {
            try
            {
                string path = @"G:\MyCodeList\CSharpPython\CSharpPython\bin\Debug\Add.py"; // *.py文件路径,不要有空格或中文
                if (!File.Exists(path)) return;

                // 两个输入参数
                int a = Convert.ToInt32(this.numericUpDown1.Text);
                int b = Convert.ToInt32(this.numericUpDown2.Text);

                // 进程启动信息
                ProcessStartInfo start = new ProcessStartInfo();
                start.FileName = @"E:\Program Files (x86)\Microsoft Visual Studio\Shared\Python37_64\python.exe"; // Python.exe,程序。可以配置环境变量,从而只使用程序名称
                start.Arguments = $"{path} {a} {b}";  // 启动程序时的输入参数,参数间使用一个空格,py代码文件路径,不要有“中文和空格”。
                start.UseShellExecute = false;
                start.RedirectStandardOutput = true;
                start.RedirectStandardInput = true;
                start.RedirectStandardError = true;
                start.CreateNoWindow = true; // 不显示界面

                // 启动进程
                var pp = new Process();
                pp.StartInfo = start;
                pp.Start();

                // 执行后输出结果
                using (var progressTest = Process.Start(start))
                {
                    progressTest.ErrorDataReceived += Pp_ErrorDataReceived;
                    // 异步获取命令行内容
                    progressTest.BeginOutputReadLine();
                    // 为异步获取订阅事件
                    progressTest.OutputDataReceived += new DataReceivedEventHandler(outputDataReceived);
                }

            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        public void outputDataReceived(object sender, DataReceivedEventArgs e)
        {
            if (!string.IsNullOrEmpty(e.Data))
            {
                this.Invoke(new Action(() =>
                {
                    this.label5.Text = e.Data; // SUM结果
                }));
            }
        }

        private void Pp_ErrorDataReceived(object sender, DataReceivedEventArgs e)
        {
            var ed = e.Data;
        }

以上,即可;运行如下图: