美文网首页c/c++pythonalready
C# 调用Python 应用程序

C# 调用Python 应用程序

作者: Ritchie_Li | 来源:发表于2022-07-26 21:05 被阅读0次

    原因:

    因为C#应程序需要从网上获取一些数据,但是C# POST请求不是很熟悉,需要去学习,但是之前自学过Python爬虫,简单几行代码就可以获取所需要的数据,3分钟就能解决问题,性能差一点没有关系,主要是实现了功能。

    1. Python实现POST请求

    在实际网站 F2,刷新,查看发送的网络请求类和发送的数据格式。在代码中构造POST数据, 完整代码如下:

    import requests

    import sys

    headers = {

    "User-Agent":"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/103.0.0.0 Safari/537.36"

    }

    url ="http://192.168.0.122:3311/UIHandler/ItemQueryHandle.ashx"

    def GetInfo(sapNr):

        data = {'action':"query",

                'ItemCode': sapNr,

                'Plant':"",

                'Desc_CH':"",

                'Item_Group':"",

                'page':1,

                'rows':30}

            response = requests.post(url=url, params=data, headers=headers)

            result = response.json()

            return result

    if __name__ =='__main__':

        print(GetInfo(sys.argv[1])) # 表示传递进来的参数,sys.argv[0]表示文件本身名字,从1开始,依次类推

        sys.stdout.flush()

    需要将Python应用打包,使用pyinstaller 打包成为,exe文件,方便C#调用。

    2. C# 调用Python应用程序

    using System.Diagnostics;

    创建一个简单的ConsoleApp测试:

                Process p = new Process();

                p.StartInfo.FileName = @"D:\CodeTest\POSTDemo\InvokePy\GetSAPInfo.exe";

                p.StartInfo.UseShellExecute = false;//必须

                p.StartInfo.RedirectStandardInput = true; //重定向标准输入,传入参数

                p.StartInfo.RedirectStandardOutput = true; //重定向标准输出

                p.StartInfo.CreateNoWindow = true; //隐藏窗体

                p.StartInfo.RedirectStandardError = true;

                p.StartInfo.Arguments = @"157999";//参数173722,178360

                p.EnableRaisingEvents = true;

                 p.Start();

                string output = p.StandardOutput.ReadToEnd();

                Console.WriteLine(output);

                p.WaitForExit();

                p.Close();

    使用Process类的实例,运行打包OK的exe文件,将SAPNr参数从C#代码传入搭到Python中,将Python应用程序请求响应数据在C#应用程序中接收,感觉大概耗时1-2秒,效率的确要差一点,但是3分钟就解决了实际的问题。

    相关文章

      网友评论

        本文标题:C# 调用Python 应用程序

        本文链接:https://www.haomeiwen.com/subject/qzfairtx.html