欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C#調(diào)用Python程序傳參數(shù)獲得返回值

 更新時間:2022年02月14日 15:13:57   作者:小龍狗  
C# 調(diào)用 Python 程序有多種方式,本文主要介紹了4種方式,文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價值,感興趣的小伙伴們可以參考一下

說明

C# 調(diào)用 Python 程序有多種方式,本篇用的是第 4 種:

  • nuget的ironPython;
  • 用 c/c++ 調(diào)用python,再封裝成庫文件,c# 調(diào)用;
  • c# 命令行調(diào)用.py文件執(zhí)行;
  • python 程序制作成 .exe 可執(zhí)行文件,c# 使用命令行進(jìn)行傳參取返回值。

1. Python 腳本

先建個測試腳本 d://Test/EchoHi.py 代碼如下:

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

測試一哈

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

2. 打包成Windows可執(zhí)行文件

首先安裝給python打包的python包

D:\Test>pip install pyinstaller

執(zhí)行打包命令,看輸出

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.

這里有生成的可執(zhí)行文件的位置,進(jìn)入可執(zhí)行文件的目錄測試

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());
    }
}

特別需要注意的是:

命令參數(shù)是 arguments 內(nèi)不能有多余空格,因為每個空格都會被識別為分割;
還要注意加一層轉(zhuǎn)義,假執(zhí)行命令為 EchoHi.exe Mr.\"Tree\" (Tree加了雙引號)時,定義就應(yīng)該為

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

此后編譯運(yùn)行即可。

4. 參考

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

到此這篇關(guān)于C#調(diào)用Python程序傳參數(shù)獲得返回值的文章就介紹到這了,更多相關(guān)C#調(diào)用Python獲得返回值內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論