With the help of the example provided from @Hornbydd I created my solution like this:
class RunProcess
{
private Process process;
private StringBuilder output = new();
private StringBuilder error = new();
public (string Output, string Error, int ErrCode) RunProcessGrabOutput(string Executable, string Arguments, string WorkingDirectory)
{
int exitCode = -1;
try
{
output.Clear();
error.Clear();
process = new Process();
process.StartInfo.FileName = Executable;
process.StartInfo.UseShellExecute = false;
process.StartInfo.WorkingDirectory = WorkingDirectory;
process.StartInfo.RedirectStandardInput = true;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
process.StartInfo.StandardErrorEncoding = Encoding.UTF8;
process.StartInfo.StandardOutputEncoding = Encoding.UTF8;
process.StartInfo.CreateNoWindow = true;
process.StartInfo.EnvironmentVariables.Add("PYTHONUNBUFFERED", "TRUE");
if (!string.IsNullOrEmpty(Arguments))
process.StartInfo.Arguments = Arguments;
process.EnableRaisingEvents = true;
process.OutputDataReceived += new DataReceivedEventHandler(ProcessOutputHandler);
process.ErrorDataReceived += new DataReceivedEventHandler(ProcessErrorHandler);
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// You can set the priority only AFTER the you started the process.
process.PriorityClass = ProcessPriorityClass.BelowNormal;
process.WaitForExit();
exitCode = process.ExitCode;
}
catch
{
// This is how we indicate that something went wrong.
throw;
}
return (output.ToString(), error.ToString(), exitCode);
}
private void ProcessOutputHandler(object SendingProcess, DataReceivedEventArgs OutLine)
{
output.AppendLine(OutLine.Data);
}
private void ProcessErrorHandler(object SendingProcess, DataReceivedEventArgs OutLine)
{
error.AppendLine(OutLine.Data);
}
}
This function is called like this:
var workingDir = "C:\\Daten\\RadSvn\\Prototypes\\StartPythonScript\\StartPythonScript\\Scripts";
var myArguments = "-c \"from Test import Main;Main('Hallo')\"";
var process = new RunProcess();
var processOutcome = process.RunProcessGrabOutput(executable,
myArguments, workingDir);
while Test.py is the name of the script and Main is a function in there which has a parameter called "dataset":
import arcpy
import string, sys, os
import ctypes
logfile ="C:\\Daten\\RadSvn\\Prototypes\\StartPythonScript\\StartPythonScript\\Scripts\\Logfile.log"
def Main(dataset):
print ("Started with argument " + dataset)
datei = open(logfile, 'a')
datei.write("Started with argument " + dataset)