目录
  • 说明
  • 1. Python 脚本
  • 2. 打包成Windows可执行文件
  • 3. C# 程序
  • 4. 参考

说明

C# 调用 Python 程序有多种方式,本篇用的是第 4 种:

  • nuget的ironPython;
  • 用 c/c++ 调用python,再封装成库文件,c# 调用;
  • c# 命令行调用.py文件执行;
  • python 程序制作成 .exe 可执行文件,c# 使用命令行进行传参取返回值。

1. Python 脚本

先建个测试脚本 d://Test/EchoHi.py 代码如下:

import sys
def EchoHi(a):
    return ("Hello, " + a)
if __name__ == "__main__":
    # print('参数列表:', str(sys.argv))
    print(EchoHi(sys.argv[1]))

测试一哈

D:\Test>python EchoHi.py Mr.Tree
Hello, Mr.Tree

2. 打包成Windows可执行文件

首先安装给python打包的python包

D:\Test>pip install pyinstaller

执行打包命令,看输出

D:\Test>pyinstaller -F EchoHi.py

21185 INFO: Writing RT_ICON 7 resource with 1128 bytes
21192 INFO: Updating manifest in D:\Test\build\EchoHi\run.exe.0u78g5s3
21444 INFO: Updating resource type 24 name 1 language 0
21447 INFO: Appending archive to EXE D:\Test\dist\EchoHi.exe
21634 INFO: Building EXE from EXE-00.toc completed successfully.

这里有生成的可执行文件的位置,进入可执行文件的目录测试

D:\Test\dist>EchoHi.exe Mr.Tree
Hello, Mr.Tree

3. C# 程序

CallCmd.cs 代码如下

using System;
class Test
{
    public static void Main(String[] args)
    {
      string cmdpath = "d://Test/dist/EchoHi.exe";
      string arguments = "Mr.Cmd";
      Console.WriteLine(CallCMD(cmdpath, arguments));
    
    }
    public static string CallCMD(string _command, string _arguments){
      System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(_command, _arguments);
      psi.CreateNoWindow = true;
      psi.RedirectStandardOutput = true;
      psi.UseShellExecute = false;
      System.Diagnostics.Process p = System.Diagnostics.Process.Start(psi);
      return(p.StandardOutput.ReadToEnd());
    }
}

特别需要注意的是:

命令参数是 arguments 内不能有多余空格,因为每个空格都会被识别为分割;
还要注意加一层转义,假执行命令为 EchoHi.exe Mr.\&;Tree\&; (Tree加了双引号)时,定义就应该为

string arguments = "\\\"Mr.Cmd\\\"";

此后编译运行即可。

4. 参考

[1] https://blog.csdn.net/qq_42063091/article/details/82418630

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。