如何在 c# 中执行并返回 python 脚本的结果? [英] How do I execute and return the results of a python script in c#?

查看:61
本文介绍了如何在 c# 中执行并返回 python 脚本的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在c#中执行并返回python脚本的结果?

How do I execute and return the results of a python script in c#?

我正在尝试从我的控制器运行 python 脚本.

I am trying to run a python script from my controller.

我在使用 virtualenv 命令创建的虚拟环境文件夹中安装了 python.exe.

I have python.exe setup in a virtual environment folder created with the virtualenv command.

所以现在只是为了测试目的,我只想从我的 phython 脚本中返回结果字符串:

So just for testing purposes at the moment I would like to just return resulting string from my phython script:

# myscript.py
print "test"

并在我的 asp.net mvc 应用程序的视图中显示.

And display that in a view in my asp.net mvc app.

我从相关的 stackoverflow 问题 中获得了 run_cmd 函数.我已经尝试添加 -i 选项来强制交互模式并调用 process.WaitForExit() 没有运气.

I got the run_cmd function from a related stackoverflow question. I've tried adding the -i option to force interactive mode and calling process.WaitForExit() with no luck.

namespace NpApp.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index(string returnUrl)
        {
            ViewBag.ReturnUrl = returnUrl;

            ViewBag.textResult = run_cmd("-i C:/path/to/virtualenv/myscript.py", "Some Input");

            return View();
        }

        private string run_cmd(string cmd, string args)
        {
            ProcessStartInfo start = new ProcessStartInfo();
            start.FileName = @"C:/path/to/virtualenv/Scripts/python.exe";
            start.CreateNoWindow = true;
            start.Arguments = string.Format("{0} {1}", cmd, args);
            start.UseShellExecute = false;
            start.RedirectStandardOutput = true;
            using (Process process = Process.Start(start))
            {
                using (StreamReader reader = process.StandardOutput)
                {
                    string result = reader.ReadToEnd();
                    //Console.Write(result);
                    process.WaitForExit();
                    return result;
                }
            }
        }
    }
}

似乎 myscript.py 从未运行过.但我没有得到任何错误,在我看来只是一个空白变量.

It seems like myscript.py never even runs. But I get no errors, just a blank variable in my view.

我曾试图简化上述内容,因为我认为解释和得到答案会更容易.最终我确实需要使用一个名为nameparser"的包并将传递的名称参数的结果存储到数据库中.但是如果我可以让 run_cmd 返回一个字符串,我想我可以处理剩下的事情.这就是为什么我认为评论中提到的其余 api 和 IronPython 在这里可能对我不起作用.

I had tried to simplify the above stuff because I thought it would be easier to explain and get an answer. Eventually I do need to use a package called "nameparser" and store the result of passed name argument into a database. But if I can just get the run_cmd to return a string I think I can take care of the rest of it. This is why I think the rest api and IronPython mentioned in the comments may not work for me here.

推荐答案

好的,我从评论中找出了问题所在.主要是python.exe 和myscript.py 路径中的空格.结果我不需要 -iprocess.WaitForExit().我只是将 python 虚拟环境移动到没有空格的路径中,一切都开始工作了.还要确保 myscript.py 文件是可执行的.

Ok, I figured out what the issue was thanks to some leads from the comments. Mainly it was the spaces in the path to the python.exe and the myscript.py. Turns out I didn't need -i or process.WaitForExit(). I just moved the python virtual environment into a path without spaces and everything started working. Also made sure that the myscript.py file was executable.

这真的很有帮助:

string stderr = process.StandardError.ReadToEnd();
string stdout = process.StandardOutput.ReadToEnd();
Debug.WriteLine("STDERR: " + stderr);
Debug.WriteLine("STDOUT: " + stdout);

这会在 Visual Studio 的输出"窗格中显示 Python 错误和输出.

That shows the python errors and output in the Output pane in Visual Studio.

这篇关于如何在 c# 中执行并返回 python 脚本的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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