Home > front end >  How to launch an external program changing directory
How to launch an external program changing directory

Time:05-30

I have to launch Python from another folder. To do that before I have to change folder. Just like if I did Cd ..pythonPath... The tasks I do are:

  1. Get Python path from the enviroment variable

     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. With that I get the script folder so I move one up

     strPythonPath =  Path.GetFullPath( Path.Combine(strPythonPath, ".."));
    
  3. I launch the external process

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

With that I get unable to find the specified file. Of course I might ALSO puth that complete path in

    ExternalProcess.StartInfo.FileName = " C:\Program Files\Python39\Phyton.exe";

but is that the right thing to do?

Once again what I would like is to move beforehand just like doing

cd  C:\Program Files\Python39

and additionally could it be Directory.SetCurrentDirectory(...) the solution?

Thanks

CodePudding user response:

Every process has its working directory, the it is inherited from the parent process by default. In your question, you metioned two working directories.

  1. ExternalProcess.StartInfo.WorkingDirectory = strPythonPath;

  2. Directory.SetCurrentDirectory(...)

The first one belongs to the external process, the second belongs to the current process. When you launch the external process (pyhton.exe), the current process will try to search the executable from its working directory (2nd) if the filename isn't an absolute path. (intricate rules in fact, it's simplified here). After the external process is launched, its working directory (1st) takes over the position.

In conclusion, you can use either SetCurrentDirectory or absolute FileName, just notice that SetCurrentDirectory will affect later processes.

  • Related