如何启动外部程序更改目录



我必须从另一个文件夹启动Python。要做到这一点,我必须先更改文件夹。就像我做Cd ..pythonPath…我做的任务是:

  1. 从环境变量

    获取Python路径
    string strPath = Environment.GetEnvironmentVariable("Path");
    string[] splitPath = strPath.Split(';');
    string strPythonPath = String.Empty;
    foreach (string path in splitPath)
    {
    if (path.ToUpper().Contains("PYTHON"))
    {
    strPythonPath = path;
    break;
    }
    }
    
  2. 这样我就得到了脚本文件夹所以我把它移到上面

    strPythonPath =  Path.GetFullPath( Path.Combine(strPythonPath, ".."));
    
  3. 启动外部进程

    Process ExternalProcess = new Process();        
    ExternalProcess.StartInfo.FileName = "Phyton.exe";
    string strPythonScript = @"C:tempscript.py";
    string strTestPool = "testPool.xml";
    ExternalProcess.StartInfo.WorkingDirectory = strPythonPath;
    ExternalProcess.StartInfo.Arguments = strPythonScript + " " + strTestPool + " " + strTemp;
    ExternalProcess.StartInfo.WindowStyle = ProcessWindowStyle.Maximized;
    ExternalProcess.Start();
    ExternalProcess.WaitForExit();
    

我无法找到指定的文件。当然,我也可以把完整的路径放在

ExternalProcess.StartInfo.FileName = " C:Program FilesPython39Phyton.exe";

但这是正确的事情吗?

再一次,我想要的是像一样提前移动

cd  C:Program FilesPython39

,另外,它可能是Directory.SetCurrentDirectory(…)的解决方案?

感谢

每个进程都有自己的工作目录,默认情况下它是从父进程继承的。在你的问题中,你提到了两个工作目录。

  1. ExternalProcess.StartInfo.WorkingDirectory = strPythonPath;

  2. Directory.SetCurrentDirectory(...)

第一个属于外部进程,第二个属于当前进程。当您启动外部进程(python .exe)时,如果文件名不是绝对路径,当前进程将尝试从其工作目录(2nd)搜索可执行文件。(实际上是复杂的规则,这里简化了)。外部进程启动后,其工作目录(1st)将接管该位置。

总之,您可以使用SetCurrentDirectory或绝对FileName,只是要注意SetCurrentDirectory将影响后面的进程。

最新更新