从c#执行Python脚本时的长路径

本文关键字:路径 脚本 执行 Python | 更新日期: 2023-09-27 18:12:32

我正在尝试从c#程序运行Python脚本。我使用微软的官方文档:https://code.msdn.microsoft.com/windowsdesktop/C-and-Python-interprocess-171378ee当我将短文件路径作为命令参数传递给我的Python脚本时,它工作得很好。但是当我输入同一个Python脚本的长路径时,进程运行,但脚本不执行。什么错了吗?下面是我使用的代码:

using System;
using System.IO;
using System.Diagnostics;
namespace CallPython
{
    class Program
    {
        static void Main(string[] args)
        {
            // full path of python interpreter 
            string python = @"C:'Anaconda2'python.exe";
            // This path will work
            string myPythonApp = @"C:'MyPython'helloworld.py";
            // This path will cause program to fail, nothing response 
            string myPythonApp = "C:''Users''My Name''Documents''Visual Studio 2015''Projects''My Project Name''helloworld.py";
            // Create new process start info 
            ProcessStartInfo myProcessStartInfo = new ProcessStartInfo(python);
            // make sure we can read the output from stdout 
            myProcessStartInfo.UseShellExecute = false;
            myProcessStartInfo.RedirectStandardOutput = true;
            myProcessStartInfo.Arguments = myPythonApp;
            Process myProcess = new Process();
            // assign start information to the process 
            myProcess.StartInfo = myProcessStartInfo;
            Debug.WriteLine("Calling Python script: " + myPythonApp);
            // start the process 
            myProcess.Start();
            StreamReader myStreamReader = myProcess.StandardOutput;
            string myString = myStreamReader.ReadLine();
            myProcess.WaitForExit();
            myProcess.Close();
            // write the output we got from python app 
            Debug.WriteLine("Value received from script: " + myString);
        }
    }
}

从c#执行Python脚本时的长路径

如果路径拼写错误,则可能导致此错误。要动态创建路径,您可以尝试执行以下命令:

  1. 你可以试试:

    Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments).
    

    这将返回documents文件夹的路径(如果其他用户将使用该程序,则路径将正确生成)。因此,您可以将路径的这一部分:"C:'Users'My Name'Documents'"留给编译器。从这里你可以继续构建到你的脚本的路径。

  2. 你可以试试:

    string path = "script.py";
    

    如果你设置了这个路径,它会从这里读取文件

"C:'Users'My Name'Documents'Visual Studio 2015'Projects'My Project Name'My Project Name'bin'Debug'script.py

"

或者你的可执行文件所在的位置。

  • 你可以使用directory . getparent () directory . getcurrentdirectory()来获取当前路径并移动到父目录,然后返回到你存储它的脚本。

    这些选项使创建动态路径更容易。

    看看这个页面的目录类with有一些很好的特性:http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

    或者environment类with有一些很好的功能来生成路径:https://msdn.microsoft.com/en-us/library/system.environment (v = vs.110) . aspx