C# 调用python
生活随笔
收集整理的這篇文章主要介紹了
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')"。?
若要調用腳本里的函數,常規寫法為:
縮成一行就是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的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Python开发一个股票类库
- 下一篇: C#操作静态路由表(增、删、改、查、遍历