使用C#调用执行Python代码

3

我想从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))

1
你需要在当前工作目录中拥有 Python 文件,或者将其添加到你的路径变量中,或者使用相对于当前工作目录的路径,或者使用绝对路径。 - juharr
你的文件在哪里?目前正在搜索文件C:\Users\protieax\PycharmProjects\untitled\venv\Scripts\request.py - Franck
2
首先,“C#找不到Python文件”是什么意思?你是否遇到了错误?如果是这样,请在此处发布错误信息。 - abarnert
@Franck 这几乎肯定不是当前工作目录。这只是指向Python可执行文件的路径。 - juharr
1个回答

0

您指定了一个U盘,可能是一个网络驱动器。我从未在这种情况下使用过网络驱动器,但我尝试了一下以找出是否存在问题。我挂载了一个标签为U的网络驱动器。运行代码后,它失败并给出了相同的错误。我建议将所需的Python脚本复制到当前工作目录中,这将使事情变得更加简单。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接