从C#调用python脚本 [英] Calling python script from C#

查看:509
本文介绍了从C#调用python脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个C#代码,该代码有助于先运行python环境,然后再执行我的python进程.但是问题是执行需要很多时间.

I have a C# code which helps to run python environment first and then it executes my python process. But the problem is it takes a lot of time to execute.

实际上,我只想传递我的值并在python脚本中执行单行代码.但是需要每次都执行所有python代码.有没有一种方法可以在外部运行python进程,并在我需要时只运行一行.

Actually i just want to pass my values and execute single line of code in python script. But need to execute all python code every time. Is there a way to run python process out side and just run the single line when i want.

我为此附上了C#代码和python进程

I attached both C# code and python process with this

C#代码

public String  Insert(float[] values)

        {
            // full path of python interpreter
            string python = @"C:\ProgramData\Anaconda2\python.exe";

            // python app to call
            string myPythonApp = @"C:\classification.py";

            // dummy parameters to send Python script 
            //int x = 2;
            //int y = 5;

            // Create new process start info
            ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);

            // make sure we can read the output from stdout
            myProcessStartInfo.UseShellExecute = false;
            myProcessStartInfo.RedirectStandardOutput = true;
            myProcessStartInfo.CreateNoWindow = true;
            myProcessStartInfo.WindowStyle = ProcessWindowStyle.Minimized;

            // start python app with 3 arguments 
            // 1st arguments is pointer to itself, 2nd and 3rd are actual arguments we want to send
            myProcessStartInfo.Arguments = myPythonApp + " " + values[0] + " " + values[1] + " " + values[2] + " " + values[3] + " " + values[4] + " " + values[5];

            Process myProcess = new Process();
            // assign start information to the process
            myProcess.StartInfo = myProcessStartInfo;


            myProcess.Start();

            // Read the standard output of the app we called. 
            // in order to avoid deadlock we will read output first and then wait for process terminate:
            StreamReader myStreamReader = myProcess.StandardOutput;
            string myString = myStreamReader.ReadLine();

            /*if you need to read multiple lines, you might use:
                string myString = myStreamReader.ReadToEnd() */

            // wait exit signal from the app we called and then close it.
            myProcess.WaitForExit();

            myProcess.Close();

            // write the output we got from python app
            Console.WriteLine("Value received from script: " + myString);
            Console.WriteLine("Value received from script: " + myString);

和python脚本

import numpy as np
import sys

val1 = float(sys.argv[1]) 
val2 = float(sys.argv[2]) 
val3 = float(sys.argv[3]) 
val4 = float(sys.argv[4]) 
val5 = float(sys.argv[5]) 
val6 = float(sys.argv[6]) 



# Load dataset
url = "F:\FINAL YEAR PROJECT\Amila\data2.csv"
names = ['JawLower', 'BrowLower', 'BrowRaiser', 'LipCornerDepressor', 'LipRaiser','LipStretcher','Emotion_Id']
dataset = pandas.read_csv(url, names=names)

# shape
# print(dataset.shape)


# class distribution
# print(dataset.groupby('Emotion_Id').size())


# Split-out validation dataset
array = dataset.values
X = array[:,0:6]
Y = array[:,6]
neigh = KNeighborsClassifier(n_neighbors=3)


neigh.fit(X, Y) 

print(neigh.predict([[val1,val2,val3,val4,val5,val6]]))

print(neigh.predict([[val1,val2,val3,val4,val5,val6]]))这是我要分立执行的代码行.

print(neigh.predict([[val1,val2,val3,val4,val5,val6]])) this is the line of code i want to execute separatly.

推荐答案

我建议您使用REST API从C#应用程序中调用python代码. 为此,您需要使用两个库:CPickle和flask

I would suggest you to use REST API to call python code from C# application. To achieve that you need to use two libraries: CPickle and flask

  1. 将代码行作为函数公开并注释
  2. 训练后序列化模型,并在预测时加载

请参考此代码,我已经在python 3.5中创建了

Please refer to this code, I have created in python 3.5

from sklearn import datasets
from sklearn.ensemble import RandomForestClassifier
import pickle
from flask import Flask, abort, jsonify, request
import numpy as np
import json

app = Flask(__name__)

@app.route('/api/create', methods=['GET'])

def create_model():
    iris = datasets.load_iris()
    x = iris.data
    y = iris.target
    model = RandomForestClassifier(n_estimators=100, n_jobs=2)
    model.fit(x, y)
    pickle.dump(model, open("iris_model.pkl", "wb"))
    return "done"


def default(o):
    if isinstance(o, np.integer):
        return int(o)
    raise TypeError


@app.route('/api/predict', methods=['POST'])
def make_predict():
    my_rfm = pickle.load(open("iris_model.pkl", "rb"))
    data = request.get_json(force=True)
    predict_request = [data['sl'], data['sw'], data['pl'], data['pw']]
    predict_request = np.array(predict_request)
    output = my_rfm.predict(predict_request)[0]
    return json.dumps({'result': np.int32(output)}, default=default)


if __name__ == '__main__':
    app.run(port=8000, debug=True)

您可以按以下方式运行它:

you can run it as:

这篇关于从C#调用python脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆