iis服务器助手广告广告
返回顶部
首页 > 资讯 > 后端开发 > Python >C#调用Python程序传参数获得返回值
  • 652
分享到

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

2024-04-02 19:04:59 652人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

目录说明1. python 脚本2. 打包成windows可执行文件3. C# 程序4. 参考说明 C# 调用 Python 程序有多种方式,本篇用的是第 4 种: nuget的ir

说明

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

到此这篇关于C#调用Python程序传参数获得返回值的文章就介绍到这了,更多相关C#调用Python获得返回值内容请搜索编程网以前的文章或继续浏览下面的相关文章希望大家以后多多支持编程网!

--结束END--

本文标题: C#调用Python程序传参数获得返回值

本文链接: https://www.lsjlt.com/news/139125.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作