visual studio 2022
python 3.10.11
- using Microsoft.Scripting.Hosting;
- using IronPython.Hosting;
- using System.Windows.Forms.Design;
-
- namespace JHCamera3D.Helper.Python
- {
- public class RunPythonHelper
- {
- public static string ExecPython()
- {
- string FileName = System.AppDomain.CurrentDomain.BaseDirectory + "PythonScript/pythonTest.py";
- string pm = "pm";
- // 创建进程对象并设置要运行的命令及参数
- var process = new Process();
- process.StartInfo.WorkingDirectory = System.AppDomain.CurrentDomain.BaseDirectory;
- process.StartInfo.FileName = "python.exe"; // python 安装路径或者添加到系统 PATH 变量后直接写"python"
- process.StartInfo.Arguments = $"-u {FileName} {pm}"; // 指定要运行的 Python 脚本文件名(包括完整路径)
-
- // 隐藏控制台窗口
- process.StartInfo.CreateNoWindow = true;
- process.StartInfo.UseShellExecute = false;
-
- // 重定向输入、输出和错误流
- process.StartInfo.RedirectStandardInput = true;
- process.StartInfo.RedirectStandardOutput = true;
- process.StartInfo.RedirectStandardError = true;
-
- // 开始进程
- process.Start();
-
- // 等待进程结束
- process.WaitForExit();
- // 获取标准输出结果
- string output = process.StandardOutput.ReadToEnd();
-
-
-
-
- Console.WriteLine(output);
- return output;
- }
-
-
-
- }
- }
Python脚本pythonTest.py
- #import open3d as o3d
- #import numpy as np
- #import matplotlib.pyplot as plt
- import copy
- import os
- import sys
- #import open3d.core as o3c
-
- #print(o3c)
- def Test(msg):
- #logger.debug(msg)
- #return ''
- #print('')
- return f"Hello {msg}"
-
- aa=Test("easyboot ")
- print(aa)
-
- if __name__ == "__main__":
- # print('param:', str(sys.argv))
- #print(EchoHi(sys.argv[1]))
- aa = Test(sys.argv[1])
- print(aa+'main')
Webapi中调用
- [SwaggerControllerOrder(2)]
- [ApiController]
- [Route("[controller]/[action]")]
- public class PythonController : ControllerBase
- {
- /// <summary>
- /// 设置是否保存GS文件 返回结果 true 保存,false 不保存
- /// </summary>
- /// <returns></returns>
- [HttpPost(Name = "RunPythonTest")]
- public string RunPythonTest()
- {
- string msg = RunPythonHelper.ExecPython();
- return msg;
- }
- }
测试返回结果