How to Launch an External Process

How to launch an external Process?

In a macos app, you may use run for launching external processes, an example might be:

1) one-shot execution:

let url = URL(fileURLWithPath:"/bin/ls")
do {
try Process.run(url, arguments: []) { (process) in
print("\ndidFinish: \(!process.isRunning)")
}
} catch {}

2) you may want to use a Process instance to be able to setup more comfortably its behaviour, doing so:

let process = Process()
process.executableURL = URL(fileURLWithPath:"/bin/ls")
process.arguments = ["-la"]
process.terminationHandler = { (process) in
print("\ndidFinish: \(!process.isRunning)")
}
do {
try process.run()
} catch {}

So I did launch the ls command (you may check your console for the result), then in the closure terminationHandler I'm getting back such process.

How to launch an external program changing directory

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.

Execute external program

borrowed this shamely from here

Process process = new ProcessBuilder("C:\\PathToExe\\MyExe.exe","param1","param2").start();
InputStream is = process.getInputStream();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line;

System.out.printf("Output of running %s is:", Arrays.toString(args));

while ((line = br.readLine()) != null) {
System.out.println(line);
}

More information here

Other issues on how to pass commands here and here

Calling a external program stop my script

You can use subprocess.Popen("C:\Program.exe").

As was done here: https://stackoverflow.com/a/32577744/7132596

How to launch an external process in C#, using a cmd window

try this:

ProcessStartInfo processToRunInfo = new ProcessStartInfo();    
processToRunInfo.Arguments = "Arguments");
processToRunInfo.CreateNoWindow = true;
processToRunInfo.WorkingDirectory = "C:\\yourDir\\";
processToRunInfo.FileName = "test.exe";
//processToRunInfo.CreateNoWindow = true;
//processToRunInfo.WindowStyle = ProcessWindowStyle.Hidden;
Process process = new Process();
process.StartInfo = processToRunInfo;
process.Start();


Related Topics



Leave a reply



Submit