从 C# .net 调用 python.py [英] calling python.py from C# .net

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

问题描述

我在从 C# 调用 python 脚本时遇到问题.我的 python 脚本根据参数 1 和参数 2 计算一个值并发送计算值.我无法获得计算值.说,例如我正在学习一个简单的 python 类并调用 C#

I have a problem in calling a python script from C#. My python script computes a value based on param 1 and param 2 and sends the computed value. I am not able to get the computed value. say, for example I am taking a simple python class and calling for C#

下面是python.py:

the below is python.py :

import argparse
class demo:

  def add(self,a,b):
     return a+b

def main(a,b):
 obj=demo()
 value=obj.add(a,b)
 print(value)
 return value

if __name__ == "__main__":
arg_parse = argparse.ArgumentParser()
arg_parse.add_argument("a")
arguments = arg_parse.parse_args()
main(arguments.a,3)

下面是调用它的 C# 代码.

below is the C# code to call it.

Process p = new Process(); 
        int a = 2;
        p.StartInfo.FileName = "C:\\Users\\xyx\\AppData\\Local\\Programs\\Python\\Python36-32\\pythonw\\python.exe";
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.UseShellExecute = false; 
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.CreateNoWindow = true;
        p.StartInfo.Arguments = "C:\\Users\\xyx\\AppData\\Local\\Programs\\Python\\Python36-32\\pythonw\\python.py "+a; parameter
        p.Start(); 
        StreamReader s = p.StandardOutput;
        standardError = s.ReadToEnd();
        output = s.ReadToEnd().Replace(Environment.NewLine, string.Empty); 

        p.WaitForExit();

由于 2,3 在 python 中被发送到 main(),我想要 '5' 回来.我不知道如何取回它.请帮忙

Since 2,3 are sent to main () in python, I want '5'back. I do not know how to get it back. Please help

推荐答案

以下代码片段对我有用:调用 Python 的 C# 代码

The following code snippet worked for me : C# code to call Python

using System;
using System.Diagnostics;
using System.IO;
namespace ScriptInterface
{
    public class ScriptRunner
    {
        //args separated by spaces
        public static string RunFromCmd(string rCodeFilePath, string args)
        {
            string file = rCodeFilePath;
            string result = string.Empty;

            try
            {

                var info = new ProcessStartInfo(@"C:\Users\xyz\AppData\Local\Programs\Python\Python37\python.exe");
                info.Arguments = rCodeFilePath + " " + args;

                info.RedirectStandardInput = false;
                info.RedirectStandardOutput = true;
                info.UseShellExecute = false;
                info.CreateNoWindow = true;

                using (var proc = new Process())
                {
                    proc.StartInfo = info;
                    proc.Start();
                    proc.WaitForExit();
                    if (proc.ExitCode == 0)
                    {
                        result = proc.StandardOutput.ReadToEnd();
                    }                    
                }
                return result;
            }
            catch (Exception ex)
            {
                throw new Exception("R Script failed: " + result, ex);
            }
        }
        public static void Main()
        {
            string args = "1 2";
            string res = ScriptRunner.RunFromCmd(@"your file path", args);

        }
    }

}

以及以下 Python 代码,它接受两个输入并返回它们的总和:

and following Python Code which takes two inputs and returns the sum of those:

import sys
def add_numbers(x,y):
   sum = x + y
   return sum

num1 = int(sys.argv[1])
num2 = int(sys.argv[2])

print(add_numbers(num1, num2))

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

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