【问题标题】:Execute python from C#从 C# 执行 python
【发布时间】:2018-06-04 17:22:54
【问题描述】:

我试图从 C# 执行一些 python 代码,所以我有这个代码:

ProcessStartInfo start = new ProcessStartInfo();
start.FileName = @"C:\Users\protieax\PycharmProjects\untitled\venv\Scripts\python.exe";
start.Arguments = "request.py 31.12.2016 01.01.2017 datatype";  // give filename, dates from the UI to python and query datatype
start.UseShellExecute = false;
start.RedirectStandardOutput = true;
using (Process process = Process.Start(start))
{
    using (StreamReader reader = process.StandardOutput)
    {
        string result = reader.ReadToEnd();
        Console.Write(result);
    }
}

它应该可以工作,但 C# 找不到 python 文件。

我应该在这两个变量中添加什么?谢谢

编辑:

ProcessStartInfo start = new ProcessStartInfo();
        start.FileName = @"U:\Documents\entsoe-py-master\tests\test_data";
        start.Arguments = "request.py 31.12.2016 01.01.2017 datatype";  // give filename, dates from the UI to python and query datatype
        start.UseShellExecute = false;
        start.RedirectStandardOutput = true;
        using (Process process = Process.Start(start))
        {
            using (StreamReader reader = process.StandardOutput)
            {
                string result = reader.ReadToEnd();
                Console.Write(result);
            }
        }

这是我根据您的答案修改的代码。我有一个新错误:

System.ComponentModel.Win32Exception: 'The system cannot find the file specified'

在线上

using (Process process = Process.Stqrt(start))

【问题讨论】:

  • 你要么需要当前工作目录中的python文件,要么在你的路径变量中,或者有一个来自当前工作目录的相对路径,或者只是一个绝对路径。
  • 你的文件在哪里?现在它正在搜索文件C:\Users\protieax\PycharmProjects\untitled\venv\Scripts\request.py
  • 首先,“C#找不到python文件”是什么意思?你有错误吗?如果是这样,请在此处发布错误。
  • @Franck 这几乎肯定不是当前工作目录。它只是 python 可执行文件的路径。

标签: c# python process


【解决方案1】:

您指定了一个 U 盘,大概是一个网络驱动器。我从来没有在这样的环境中使用过网络驱动器,但我尝试了它以找出问题所在。我安装了一个以 U 为标签的网络驱动器。运行代码后,它失败并给了我同样的错误。我建议将所需的 python 脚本副本复制到您当前的工作目录中,这会使事情变得更简单。

【讨论】:

    猜你喜欢
    • 2017-03-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-05
    • 2021-12-12
    • 1970-01-01
    • 1970-01-01
    • 2012-04-25
    • 2016-07-12
    相关资源
    最近更新 更多