首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#与Python之间的通信

C#与Python之间的通信
EN

Stack Overflow用户
提问于 2018-06-11 02:17:10
回答 1查看 1.5K关注 0票数 3

我在C#和Python之间的通信有一点问题。

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

代码语言:javascript
复制
    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文件,然后它才能真正做任何有用的事情(不要介意不必要的导入,我只是重用了其他文件中的内容):

代码语言:javascript
复制
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#只传递命令给它,因为每次我需要处理一条消息时重新初始化脚本花费的时间太长了。

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

EN

回答 1

Stack Overflow用户

发布于 2018-06-11 02:58:31

试试IronPython,它是一个.Net - Python桥。或者,您可以从python访问.net内容,或者从c#解释python。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50786727

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档