日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > C# >内容正文

C#

C# 调用python

發布時間:2023/11/30 C# 42 豆豆
生活随笔 收集整理的這篇文章主要介紹了 C# 调用python 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.C# 調用python

本質上是使用命令行運行python

1.1 C# 使用命令行

program.cs

using System; using System.Diagnostics; using System.IO;namespace test {class Program{static void Main(string[] args){Program p = new Program();string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");Console.WriteLine(result);Console.ReadKey();}public string run_cmd(string program, string cmd){ProcessStartInfo start = new ProcessStartInfo();start.FileName = program;start.Arguments = cmd;start.UseShellExecute = false; // Do not use OS shellstart.CreateNoWindow = true; // We don't need new windowstart.RedirectStandardOutput = true; // Any output, generated by application will be redirected backstart.RedirectStandardError = true; // Any error in standard output will be redirected back (for example exceptions)using (Process process = Process.Start(start)){using (StreamReader reader = process.StandardOutput){string result = process.StandardError.ReadToEnd();if (result == null || result == ""){result = reader.ReadToEnd();}return result;}}}} }

代碼運行結果?

  • 調用run_cmd相當于執行了cmd命令,所以就有了使用命令行運行python腳本的方式

1.2. C# 調用 python3腳本

假設C盤根目錄下有如下腳本?test1.py

import sysdef add(a,b):return a+bif __name__ == "__main__":print(sys.argv[1])print("hello python")

在?program.cs?中加入函數runPython,并修改main函數

static void Main(string[] args) {Program p = new Program();//string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");string result = p.runPython("C:\\test1.py", "\"Form C#:\"");Console.WriteLine(result);Console.ReadKey(); }public string runPython(string filename, string cmd) {string cmd1 = string.Format("{0} {1}", filename, cmd);return run_cmd("python.exe", cmd1); }

代碼運行結果?

1.3 C# 調用python3內的函數

我們知道使用python -c可以直接執行python代碼,所以合理構造語句就可以直接調用python腳本內的函數了:python -c "print('hello python')"。?
若要調用腳本里的函數,常規寫法為:

import sys sys.path.append('c:\\') import test1 print(test1.add(3,4))

縮成一行就是python -c "import sys;sys.path.append('c:\\');import test1;print(test1.add(3,4))"

在?program.cs?中加入函數runPyFunc,并修改main函數

static void Main(string[] args){Program p = new Program();//string result = p.run_cmd("ping.exe", "8.8.8.8 -n 2");//string result = p.runPython("C:\\test.py", "\"Form C#:\"");string result = p.runPyFunc(@"C:\\","test1","add","3,4");Console.WriteLine(result);Console.ReadKey();}public string runPyFunc(string path, string filename, string functionname, string parameter){string cmd = string.Format("-c \"import sys;sys.path.append('{0}');import {1};print({1}.{2}({3}))\"", path, filename, functionname, parameter);return run_cmd("python.exe", cmd);}

運行就可以得到結果“7”了

總結

以上是生活随笔為你收集整理的C# 调用python的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。