C#调用Python程序传参数获得返回值

说明

  • C# 调用 Python 程序有多种方式,本篇用的是第 4 种:
  1. nuget的ironPython;
  2. 用 c/c++ 调用python,再封装成库文件,c# 调用;
  3. c# 命令行调用.py文件执行;
  4. 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.youkuaiyun.com/qq_42063091/article/details/82418630

.
.
.
.
.
.


桃花仙人种桃树,又摘桃花换酒钱_

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值