c#调用python代码

 c#调用python的方法比较多,比如ironpython,尽管不用安装python环境,可是不兼容python众多的包,也只更新到了python2,通过创建python进程这种方式可以很好的解决兼容性问题。

    创建python进程需要安装python环境,事实上就是通过python执行的结果,返回给c#.这种比较适合用python写算法,c#来做可视化界面,可以实现程序算法和UI分离,也减少了工作量,程序的可读性也会增强。

   借鉴了这一个网站:upload/201901241015598688.gif" alt="复制代码" style="max-width: 900px; height: auto; border: none !important;" />

#!/usr/bin/envimport sys   def main():     if len(sys.argv) >= 3:         x = sys.argv[1]         y = sys.argv[2]         # print concatenated parameters        print(x+y)   if __name__ == '__main__':     main()

复制代码

   c#代码如下:(根据创建python文件的路径和python.exe的路径去做对应部分的修改)

复制代码
using System; using System.Diagnostics; using System.IO; using System.Threading.Tasks;  namespace ExecutingPythonScript {     class EntryPoint     {         static void Main(string[] args)         {              int x = 1;             int y = 2;             string progToRun = "‪E:\\hello1.py";             char[] spliter = { '\r' };              Process proc = new Process();             proc.StartInfo.FileName = "E:/install smallsize software/python3.6.5/python.exe";             proc.StartInfo.RedirectStandardOutput = true;             proc.StartInfo.UseShellExecute = false;              // call hello.py to concatenate passed parameters            proc.StartInfo.Arguments = string.Concat("E:/hello1.py", " ", x.ToString(), " ", y.ToString());             proc.Start();              StreamReader sReader = proc.StandardOutput;             string[] output = sReader.ReadToEnd().Split(spliter);              foreach (string s in output)                 Console.WriteLine(s);              proc.WaitForExit();              Console.ReadLine();         }     } }
复制代码

 

结果如下:

 https://www.cnblogs.com/cysisu/p/10312893.html

50000+
5万行代码练就真实本领
17年
创办于2008年老牌培训机构
1000+
合作企业
98%
就业率

联系我们

电话咨询

0532-85025005

扫码添加微信