【问题标题】:Calling python script from C#从 C# 调用 python 脚本
【发布时间】:2017-11-02 12:26:04
【问题描述】:

我有一个 C# 代码,它首先帮助运行 python 环境,然后它执行我的 python 进程。但问题是执行需要很长时间。

实际上我只是想传递我的值并在 python 脚本中执行单行代码。但是每次都需要执行所有的python代码。有没有办法在外面运行 python 进程并在我想要的时候运行单行。

我用这个附加了 C# 代码和 python 进程

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]])) 这是我要单独执行的代码行。

【问题讨论】:

标签: c# python machine-learning ipc


【解决方案1】:

您为什么不实际使用 Python 来运行代码,而不是嵌入到 C# 中?您将如何在具有 Python 依赖项的另一台机器上进行部署?

如果您想构建机器学习模型,有很多框架,例如 http://accord-framework.net/ 用于经典机器学习算法

也试试我的项目:deepakkumar1984/SiaNet (https://github.com/deepakkumar1984/SiaNet) 它是一个带有 CNTK 后端的 C# 包装器。尝试像包装器一样实现 keras。希望对您有所帮助!

【讨论】:

    【解决方案2】:

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

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

    请参考这段代码,我是在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)
    

    你可以这样运行它:

    【讨论】:

    • 因为我通过 C# 进程运行 python 脚本,所以它在结束时关闭。当我想运行“预测”时,需要从头开始运行。即使在这里如何保持python脚本活着并每次都调用预测?如果你也可以请添加C#调用函数,将有助于理解
    【解决方案3】:

    您需要创建一个新进程才能调用您的程序。

    看看这个:C# equivalent to fork()/exec()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-06-25
      • 2023-03-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-03-25
      • 2021-10-19
      • 2016-03-02
      相关资源
      最近更新 更多