C# 启动 a Python Web Server with Flask

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C# 启动 a Python Web Server with Flask

androllen   2020-01-08 我要评论

概览

最近有个需求是通过c#代码来启动python 脚本。嘿~嘿!!!
突发奇想~~既然可以启动python脚本,那也能启动flask,于是开始着手操作。
先看一波gif图

通过打开控制台启动flask web程序
首先我们应该准备!

准备

因为客户机系统安装的都是纯净版本,往往缺少一部分组件,所以我们在纯净的环境下需要准备必备组件:
dotnet-sdk-3.1.100-win-x64.exe

实现

通过Process来启动flask的server.py

cmd
cd Desktop
mkdir test
cd test
code .
ctrl + j 
dotnet new console
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;

namespace tes
{
  class Program
  {
    private static string _basePath => AppDomain.CurrentDomain.BaseDirectory;
    private static string _srcPath => Path.Combine(_basePath, @"AnWorker\src");
    private static string _venvPath => Path.Combine(_basePath, @"AnWorker\venv");
    static void Main(string[] args)
    {
      // string fileName = Path.Combine(_venvPath, "Scripts", "python.exe");
      // string arguements = Path.Combine(_srcPath, "server.py");
   
      var workPath = Path.Combine(_venvPath, "Scripts");
      var fileName = Path.Combine(workPath, "python.exe");
      var arguements = Path.Combine(_srcPath, "server.py");
      Console.WriteLine(fileName);
      Console.WriteLine(arguements);

      var psi = new ProcessStartInfo(fileName)
      {
        Arguments = arguements,
        WorkingDirectory = _venvPath,
        ErrorDialog = false,
        UseShellExecute = false
      };


      var path = psi.EnvironmentVariables["PATH"];
      if (path != null)
      {
        var arrayt = path.Split(new[] { ';' }).Where(p => !p.ToLower().Contains("python")).ToList();
        arrayt.AddRange(new[] { _venvPath, Path.Combine(_venvPath, "Lib") });
        psi.EnvironmentVariables["PATH"] = string.Join(";", arrayt);
      }


      Process.Start(psi);

      Console.ReadLine();
    }
  }
}

图1

图2

结构说明与配置

AnWorker 脚本网站的代码结构(看图1图2)需要说明几点

  • venv 是虚拟环境,学过Python的都明白
    • /venv/Lib 把Python 3的系统依赖库(Python\Python37\Lib 此文件夹下 除 site-packages 文件夹)存放在里面,不然启动不成功
    • /venv/DLLs (不然则会缺少一大堆的模块在路上)
    • /venv/Scripts 替换掉原有的虚拟环境
  • doc 是存放文档
  • src 是源码

结束

阐述下自己的观点,看官可能会问到干嘛不直接F5,其不是更好,最后发现没有一点diao用,我想说:存在即合理
现在Python应用很广,任何语言都有可能会使用到脚本开发。
这个时候,C# 调用Python 应运而生!安排~

下载地址:https://github.com/androllen/AnWorker

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们