在C#和Python之间进行通信

时间:2018-06-10 18:17:10

标签: c# python

我在C#和Python之间的沟通方面遇到了一些问题。

我使用以下hacky代码将一些参数从C#传递给Python:

    string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase).Substring(6);
    string pyUnintelligibilityPath = "\\unintelligibility.py";
    string pyNeuralPredictorPath = "\\predict.py";
    string clf = "\\clf.pkl";

    public double unintelligibleProbability(string pyLocation, string msg)
    {
        FileStream tempMessage = new FileStream(path + "\\tempMessage.txt", FileMode.Create);
        StreamWriter writer = new StreamWriter(tempMessage);
        writer.WriteLine(msg);
        writer.Close();

        string args = path + pyUnintelligibilityPath + " " + path + clf + " " + path + "\\tempMessage.txt" + " " + path + "\\tempCoefficient.txt";
        ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = pyLocation;
        start.Arguments = args;
        start.UseShellExecute = false;
        start.RedirectStandardOutput = false;
        start.RedirectStandardError = false;
        Process process = Process.Start(start);
        Thread.Sleep(5000);
        double unintelligibility = Convert.ToDouble(File.ReadAllText(path + "\\tempCoefficient.txt").Replace('.', ','));

        return unintelligibility;
    }

不幸的是,这个解决方案在我的情况下非常低效(甚至不是因为我没有任何代码可以检查文件是否会发生变化,因为稍后会添加它并且它不是真的我遇到的问题。

问题是,Python代码需要花费很长时间来加载.pkl文件才能实际执行任何有用的操作(不要介意不必要的导入,我只是从其他文件重用这个东西):

from sklearn.feature_extraction.text import TfidfTransformer, CountVectorizer, TfidfVectorizer
from sklearn.linear_model import LogisticRegression, SGDClassifier
from sklearn.svm import LinearSVC
from sklearn.cross_validation import cross_val_score
from sklearn.pipeline import Pipeline
from sklearn.decomposition import NMF, TruncatedSVD
from sklearn.ensemble import RandomForestClassifier, GradientBoostingClassifier
from sklearn.pipeline import FeatureUnion
from sklearn.externals import joblib
import numpy as np
import pandas as pd
import codecs
import sys

clf = joblib.load(sys.argv[1])

data = codecs.open(sys.argv[2], encoding='utf-8', mode='r')
text = data.readlines()
data.close()
text = [x.strip() for x in text] 

f = open(sys.argv[3], mode='w')

proba = clf.predict_proba(text)
for i in range(0, len(text)):
    meme = proba[i,:]
    memeNum = meme[1]/(meme[0]+meme[1])
    f.write(str(memeNum.round(4)) + "\n")
f.close()

我的问题是,是否有可能以允许我在后台运行Python脚本的方式重新编写代码,而C#只是将命令传递给它,因为每次我需要处理一个脚本时重新初始化脚本单个消息需要太长时间。

请记住,我真的不想使用任何基于网络协议的解决方案,因为这会使事情过于复杂,以至于它对我来说并不值得,我真的不在乎远程或类似的事情,一切都在本地发生。但是,如果它是唯一的选择,那么我想我别无选择。

1 个答案:

答案 0 :(得分:0)

试试IronPython,它是一个.Net - Python桥。或者基本上你可以从python访问.net的东西或者从c#中解释python。