public void ExecuteSync(string fileName, string arguments, string workingDirectory) { if (string.IsNullOrWhiteSpace(fileName)) throw new ArgumentException("fileName"); var process = new Process { StartInfo = { FileName = fileName, Arguments = arguments, WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false, WorkingDirectory = workingDirectory }, }; process.OutputDataReceived += Process_OutputDataReceived; process.ErrorDataReceived += Process_ErrorDataReceived; process.Exited += Process_Exited; try { process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } catch (Win32Exception) { throw new ExecuteFileNotFoundException(fileName); } }
public void Pack_Works() { string pathToNuGet = MakeAbsolute(@".nuget\NuGet.exe"); string pathToNuSpec = MakeAbsolute(@"src\app\SharpRaven\SharpRaven.nuspec"); ProcessStartInfo start = new ProcessStartInfo(pathToNuGet) { Arguments = String.Format( "Pack {0} -Version {1} -Properties Configuration=Release -Properties \"ReleaseNotes=Test\"", pathToNuSpec, typeof(IRavenClient).Assembly.GetName().Version), CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, WindowStyle = ProcessWindowStyle.Hidden, }; using (var process = new Process()) { process.OutputDataReceived += (s, e) => Console.WriteLine(e.Data); process.ErrorDataReceived += (s, e) => Console.WriteLine(e.Data); process.StartInfo = start; Assert.That(process.Start(), Is.True, "The NuGet process couldn't start."); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(3000); Assert.That(process.ExitCode, Is.EqualTo(0), "The NuGet process exited with an unexpected code."); } }
private void CoExecProcess(string arguments) { isRunning = true; System.Diagnostics.Process process = new System.Diagnostics.Process(); #if UNITY_EDITOR_OSX process.StartInfo.FileName = string.Format("{0}/Contents/MacOS/Unity", UnityEditorPath); #elif UNITY_EDITOR_WIN process.StartInfo.FileName = UnityEditorPath; #endif process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputHandler); process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorOutputHanlder); process.StartInfo.RedirectStandardInput = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.Arguments = arguments; process.EnableRaisingEvents = true; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); }
public Dictionary<string, EngineConfigEntry> GetEngineConfigOptions(SpringPaths paths, string engine) { Trace.TraceInformation("Extracting configuration from Spring located in {0}", paths.GetEngineFolderByVersion(engine)); var sb = new StringBuilder(); var p = new Process(); p.StartInfo.CreateNoWindow = true; p.StartInfo.UseShellExecute = false; p.StartInfo.Arguments += string.Format("--list-config-vars"); p.StartInfo.EnvironmentVariables["SPRING_DATADIR"] = paths.WritableDirectory; p.StartInfo.EnvironmentVariables.Remove("SPRING_ISOLATED"); p.StartInfo.FileName = paths.GetSpringExecutablePath(engine); p.StartInfo.WorkingDirectory = Path.GetDirectoryName(paths.GetSpringExecutablePath(engine)); p.StartInfo.RedirectStandardOutput = true; p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data); p.Start(); p.BeginOutputReadLine(); p.WaitForExit(3000); sb.AppendLine(); //append terminator var text = sb.ToString(); int whereIsTable = text.IndexOf('{'); text = text.Substring(whereIsTable); // skip empty line or other info (if exist). Compatibility with Spring 94+ var data = JsonConvert.DeserializeObject<Dictionary<string, EngineConfigEntry>>(text); return data; }
public static void ExecuteCommand(ExecutableInfo _info) { Debug.WriteLine($"Execucting: {_info.Command}"); //var processInfo = new ProcessStartInfo("cmd.exe", "/c " + _info.Command); var processInfo = new ProcessStartInfo("openvpn.exe", _info.Command); //processInfo.WorkingDirectory = _info.WorkingDirectory; processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardError = true; processInfo.RedirectStandardOutput = true; Process process = new Process(); process.StartInfo = processInfo; process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine(e.Data); process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => Console.WriteLine(e.Data); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); }
public static void Install() { string filename = GetOsDependantFilename(); var startInfo = new ProcessStartInfo(filename, InstallArgs) { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, WorkingDirectory = Path.GetTempPath() }; using (var process = new Process()) { var output = new StringBuilder(); process.StartInfo = startInfo; process.OutputDataReceived += (sender, e) => { if (e.Data != null) output.AppendLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); ParseForElevatedPermissionsError(output.ToString()); Console.Out.WriteLine(output.ToString()); } }
protected async Task StartProcessAsync(CancellationToken cancellationToken) { StopProcess(ref this.process); var process = new Process(); try { process.OutputDataReceived += _process_OutputDataReceived; process.Exited += _process_Exited; process.EnableRaisingEvents = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; await ConfigureProcessAsync(process.StartInfo, cancellationToken); eventSource.Message($"{process.StartInfo.FileName} {process.StartInfo.Arguments}"); if (!process.Start()) throw new Exception("could not start process"); process.BeginOutputReadLine(); } catch { StopProcess(ref process); throw; } this.process = process; }
/// <summary> /// Not Completely Implemented /// </summary> /// <param name="processPath"></param> /// <param name="processArguments"></param> /// <param name="startProcess"></param> /// <param name="waitForExit"></param> /// <param name="processDataCapturer"></param> /// <returns></returns> public static Process LaunchExternalProcess(string processPath, string processArguments, bool startProcess, bool waitForExit, IProcessDataCapturer processDataCapturer) { var externalProcess = new Process(); var externalProcessStartInfo = new ProcessStartInfo { Arguments = processArguments, FileName = processPath, RedirectStandardInput = true, RedirectStandardError = true, RedirectStandardOutput = true, CreateNoWindow = true, UseShellExecute = false }; externalProcess.StartInfo = externalProcessStartInfo; if (processDataCapturer != null) { processDataCapturer.Process = externalProcess; } if (startProcess) { externalProcess.Start(); } if (processDataCapturer != null && startProcess) { externalProcess.BeginOutputReadLine(); externalProcess.BeginErrorReadLine(); } if (waitForExit) externalProcess.WaitForExit(); return externalProcess; }
private static bool run(string exec, string[] args) { log_str_ = new System.Text.StringBuilder(); var process = new System.Diagnostics.Process(); process.StartInfo.FileName = exec; process.StartInfo.RedirectStandardOutput = true; #if UNITY_EDITOR_WIN process.StartInfo.EnvironmentVariables["VisualStudioVersion"] = "14.0"; #endif process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputHandler); process.StartInfo.UseShellExecute = false; process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorOutputHanlder); process.StartInfo.CreateNoWindow = true; process.StartInfo.Arguments = string.Join(" ", args); process.EnableRaisingEvents = true; process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); if (log_str_.Length > 0) { log_str_.Append("done. " + System.DateTime.Now + "\n"); Debug.Log(log_str_.ToString()); } var success = (process.ExitCode == 0); if (success) { Debug.LogFormat("[{0} {1}] {2}", exec, string.Join(" ", args), "done."); } else { Debug.LogErrorFormat("[{0} {1}] {2}", exec, string.Join(" ", args), "failed."); } return(success); }
// start process, execute mldb command, return terminal output void ExecuteMLDBCommand(string command, string args) { // display command to user hasExited = false; p = new System.Diagnostics.Process(); p.StartInfo.WorkingDirectory = sdkPath + "/tools/mldb/"; p.StartInfo.FileName = "mldb.exe"; // make sure user can't initiate an infinite log, and reset output whenever log is called so we can show the whole 100 lines if (command == "log") { terminalOutput = ""; log = ""; if (args == "") { args = "-d -t 100"; terminalOutput += "No support for continuous logging yet. Default log gives 100 lines."; } } p.StartInfo.Arguments = command + " " + args; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.RedirectStandardOutput = true; p.Exited += new System.EventHandler(handleExit); p.EnableRaisingEvents = true; p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler( (s, e) => { string output = e.Data; prevMessage = output; switch (command) { case "log": terminalOutput += output; terminalOutput += "\n"; log += output + "\n"; break; default: terminalOutput += output; terminalOutput += "\n"; break; } // set scrollbar position to bottom when new data is received scroll.y = 10000; // if terminal output is too long, empty it if (terminalOutput.Length >= 16382) { terminalOutput = ""; } } ); terminalOutput += "mldb " + command + " " + args + "\n"; p.Start(); p.BeginOutputReadLine(); }
private Process ExecuteCore(string file, string arguments) { if (string.IsNullOrEmpty(file)) throw new ArgumentNullException("file"); _messages.Write(string.Format("Starting {0} {1}\n", file, arguments)); System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo() { UseShellExecute = false, WorkingDirectory = _basePath, CreateNoWindow = true, WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden, FileName = Path.Combine(_basePath, file), Arguments = arguments, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = true, }; var process = new System.Diagnostics.Process(); process.StartInfo = psi; process.OutputDataReceived += (s, e) => _syncCtx.Post(state => { _messages.WriteLine(e.Data); }, null); process.ErrorDataReceived += (s, e) => _syncCtx.Post(state => { _messages.WriteLine(e.Data); }, null); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); return process; }
public static void RunProcess(string name, string args, IList<string> stdout) { var processStartInfo = new ProcessStartInfo { CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardInput = true, UseShellExecute = false, FileName = name, Arguments = args }; var process = new Process { StartInfo = processStartInfo, EnableRaisingEvents = true }; process.OutputDataReceived += delegate (object sender, DataReceivedEventArgs e) { stdout.Add(e.Data); Console.WriteLine(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); process.CancelOutputRead(); }
public static void openFeeddownload(string torrentclient, string folder, string link) { var sta = new Process(); var downloadsafe = folder.Trim(); Debug.Write(downloadsafe); //"add -p 'D:/Program Files (x86)/Deluge' 'D:/Development/python34/Anime checker/torrents/[HorribleSubs] Hibike! Euphonium - 13 [720p].mkv.torrent'" var call = $"\"add -p '{downloadsafe}' '{link.Replace("https", "http")}'\""; call = call.Replace(@"\\", "/"); call = call.Replace(@"\", "/"); sta.StartInfo.FileName = torrentclient; sta.StartInfo.Arguments = call; sta.StartInfo.RedirectStandardOutput = true; sta.StartInfo.RedirectStandardError = true; sta.EnableRaisingEvents = true; sta.StartInfo.CreateNoWindow = true; // see below for output handler sta.ErrorDataReceived += proc_DataReceived; sta.OutputDataReceived += proc_DataReceived; sta.StartInfo.UseShellExecute = false; sta.Start(); sta.BeginErrorReadLine(); sta.BeginOutputReadLine(); sta.WaitForExit(); }
public static void Start(string fileName, string arguments = null, string workingDirectory = null) { var startInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, WorkingDirectory = workingDirectory, UseShellExecute = false, CreateNoWindow = true, RedirectStandardError = true, RedirectStandardOutput = true }; using (var process = new Process { StartInfo = startInfo, EnableRaisingEvents = true }) { process.ErrorDataReceived += Log; process.OutputDataReceived += Log; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); process.WaitForExit(); } }
/// <summary> /// Compile the specified grammar /// </summary> /// <param name="grammarFile">Grammar file to compile</param> /// <param name="outputFile">The name of the binary file output</param> /// <remarks>The GOLD compiler outputs 2 versions of binary grammar tables: /// CGT and EGT. The format generated depends on the file extension of the /// output file (.cgt or .egt)</remarks> public void Compile(string grammarFile, string outputFile) { //create a helper that will classify the error messages emitted by GOLD inputFileName = grammarFile; string text = slurpFile (inputFileName); outputParser = new GoldBuildOutputParser (inputFileName); //perform an initial parse on the file. //this will get the error locations for us, //since we can't get this info from the gold compiler parser.Parse (text); //launch the GOLD command line compiler startInfo.Arguments = constructArguments (grammarFile, outputFile); startInfo.WorkingDirectory = Path.GetDirectoryName (outputFile); var p = new Process(); p.StartInfo = startInfo; p.OutputDataReceived += outputHandler; try { p.Start(); p.BeginOutputReadLine(); p.BeginErrorReadLine(); p.WaitForExit(); p.Close(); } catch(Win32Exception) { var message = new CompilerMessage (MessageSeverity.Error, goldCmdPath + " was not found on path", string.Empty, 0, 0); onCompileStepComplete (message); } }
protected override void OnStart(string[] args) { var syslog = Syslog.Build(Config.Params(), eventSource); process = new Process { StartInfo = { FileName = "garden-windows.exe", Arguments = "--listenNetwork=tcp -listenAddr=0.0.0.0:9241 -containerGraceTime=5m -containerizerURL=http://localhost:1788", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, } }; process.EnableRaisingEvents = true; process.Exited += process_Exited; process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { EventLog.WriteEntry(eventSource, e.Data, EventLogEntryType.Information, 0); if (syslog != null) syslog.Send(e.Data, SyslogSeverity.Informational); }; process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { EventLog.WriteEntry(eventSource, e.Data, EventLogEntryType.Warning, 0); if (syslog != null) syslog.Send(e.Data, SyslogSeverity.Warning); }; EventLog.WriteEntry(eventSource, "Starting", EventLogEntryType.Information, 0); EventLog.WriteEntry(eventSource, ("Syslog is " + (syslog==null ? "NULL" : "ALIVE")), EventLogEntryType.Information, 0); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
public void run() { var executableName = "starbound_server" + (StarryboundServer.IsMono ? "" : ".exe"); try { ProcessStartInfo startInfo = new ProcessStartInfo(executableName) { WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; process = Process.Start(startInfo); StarryboundServer.parentProcessId = process.Id; File.WriteAllText("starbound_server.pid", process.Id.ToString()); process.OutputDataReceived += (sender, e) => parseOutput(e.Data); process.ErrorDataReceived += (sender, e) => logStarboundError("ErrorDataReceived from starbound_server.exe: " + e.Data); process.BeginOutputReadLine(); process.WaitForExit(); StarryboundServer.serverState = ServerState.Crashed; } catch (ThreadAbortException) { } catch (Exception e) { StarryboundServer.logException("Unable to start starbound_server.exe, is this file in the same directory? " + e.ToString()); StarryboundServer.serverState = ServerState.Crashed; } }
public bool RunCommandAndGetOutput(string command, string arguments, string workingFolder) { var p = new Process(); p.StartInfo.FileName = command; p.StartInfo.Arguments = arguments; p.StartInfo.WorkingDirectory = workingFolder; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.CreateNoWindow = true; p.OutputDataReceived += OutputDataReceived; try { p.Start(); } catch { return false; } p.BeginOutputReadLine(); // Async reading of output to prevent deadlock if (p.WaitForExit(5000)) { return p.ExitCode == 0; } return false; }
public static void Main(string[] args) { var psi = new ProcessStartInfo() { FileName = args[0], RedirectStandardError = true, RedirectStandardOutput = true, UseShellExecute = false }; var process = new Process() { StartInfo = psi }; process.OutputDataReceived += (sender, a) => { ProcessData(a.Data, Console.Out); }; process.ErrorDataReceived += (sender, a) => { ProcessData(a.Data, Console.Error); }; process.EnableRaisingEvents = true; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); }
public void run() { if (!File.Exists(exe)) return; list.Add(this); process = new Process(); try { process.EnableRaisingEvents = true; process.Exited += new EventHandler(runFinsihed); process.StartInfo.FileName = Main.IsMono ? exe : wrapQuotes(exe); process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += new DataReceivedEventHandler(OutputDataHandler); process.StartInfo.RedirectStandardError = true; process.ErrorDataReceived += new DataReceivedEventHandler(OutputDataHandler); process.StartInfo.Arguments = arguments; process.Start(); // Start the asynchronous read of the standard output stream. process.BeginOutputReadLine(); process.BeginErrorReadLine(); } catch (Exception e) { Main.conn.log(e.ToString(), false, 2); list.Remove(this); } }
/// <summary> /// Executes process and capture its output. /// </summary> /// <param name="processStartInfo">The process start information.</param> /// <param name="output">The output.</param> /// <returns></returns> public static Process ExecuteAndCaptureOutput(ProcessStartInfo processStartInfo, out string output) { processStartInfo.CreateNoWindow = true; processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardOutput = true; processStartInfo.RedirectStandardError = true; var process = new Process { StartInfo = processStartInfo }; var outputBuilder = new StringBuilder(); process.OutputDataReceived += (sender, args) => { lock (outputBuilder) { if (args.Data != null) outputBuilder.AppendLine(args.Data); } }; process.ErrorDataReceived += (sender, args) => { lock (outputBuilder) { if (args.Data != null) outputBuilder.AppendLine(args.Data); } }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); output = outputBuilder.ToString(); return process; }
public static AsyncProcess Start(ProcessStartInfo startInfo, IDictionary environment) { startInfo.RedirectStandardError = true; startInfo.RedirectStandardOutput = true; startInfo.UseShellExecute = false; if (environment != null) { foreach (var i in environment.Keys) { startInfo.EnvironmentVariables[(string)i] = (string)environment[i]; } } var process = new Process { StartInfo = startInfo }; var result = new AsyncProcess(process); process.EnableRaisingEvents = true; // set up std* access process.ErrorDataReceived += (sender, args) => result._stdError.Add(args.Data); process.OutputDataReceived += (sender, args) => result._stdOut.Add(args.Data); process.Exited += (sender, args) => { result._stdError.Completed(); result._stdOut.Completed(); }; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); return result; }
public CmdResult Run() { Process proc = new Process(); proc.StartInfo.FileName = "cmd.exe"; proc.StartInfo.Arguments = "/c " + _command; if(!string.IsNullOrEmpty(_runFrom)) proc.StartInfo.WorkingDirectory = _runFrom; proc.StartInfo.UseShellExecute = false; proc.StartInfo.CreateNoWindow = true; proc.StartInfo.RedirectStandardOutput = true; proc.StartInfo.RedirectStandardError = true; proc.OutputDataReceived += new DataReceivedEventHandler(proc_OutputDataReceived); proc.ErrorDataReceived += new DataReceivedEventHandler(proc_ErrorDataReceived); WriteLog(_command); proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); proc.WaitForExit(); var result = new CmdResult(_command, proc.ExitCode, _output.ToString()); proc.Close(); WriteLog("exit code: " + result.ExitCode); return result; }
public static string RunCommand(string command, string cwd) { var process = new Process { StartInfo = new ProcessStartInfo("cmd") { Arguments = "/C " + command, RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, WorkingDirectory = cwd, CreateNoWindow = true } }; var output = ""; process.OutputDataReceived += delegate(object o, DataReceivedEventArgs args) { if (args.Data == null) return; output += args.Data; if (args.Data[args.Data.Length - 1] != '\n') output += '\n'; }; process.ErrorDataReceived += delegate(object o, DataReceivedEventArgs args) { output += args.Data; }; process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); while (!process.HasExited) Thread.Sleep(10); return output; }
public static bool Start() { var filename = Os.Tools.GetFullPath(VBusMonitorExecutable); if (string.IsNullOrWhiteSpace(filename)) return false; try { Stop(); VBusMonitorProcess = new Process(); VBusMonitorProcess.StartInfo.UseShellExecute = false; VBusMonitorProcess.StartInfo.RedirectStandardOutput = true; VBusMonitorProcess.StartInfo.FileName = filename; VBusMonitorProcess.StartInfo.Arguments = VBusMonitorParameters; VBusMonitorProcess.OutputDataReceived += VBusMonitorOnDataReceived; VBusMonitorProcess.Start(); VBusMonitorProcess.BeginOutputReadLine(); } catch { return false; } return true; }
public static void Run(string testArgument, DataReceivedEventHandler dataReceived = null) { string jarArgs = String.Format("{0} {1}", JavaArgs, testArgument); var processInfo = new ProcessStartInfo(JavaExecutable, jarArgs) { CreateNoWindow = true, UseShellExecute = false, // redirected streams // redirect output stream RedirectStandardOutput = true, RedirectStandardError = true, RedirectStandardInput = true }; _process = new Process { StartInfo = processInfo, EnableRaisingEvents = true }; _process.OutputDataReceived += ProcessOnOutputDataReceived; _process.ErrorDataReceived += ProcessOnErrorDataReceived; if (dataReceived != null) { _process.OutputDataReceived += dataReceived; _process.ErrorDataReceived += dataReceived; } _process.Start(); Trace.WriteLine("Java process started."); _process.BeginOutputReadLine(); _process.BeginErrorReadLine(); Trace.WriteLine("Waiting for Java process to exit."); _process.WaitForExit(); Trace.WriteLine("Java process exited."); _process.Close(); }
public virtual string ConvertFile(Episode episode, ProgressNotification notification) { _notification = notification; _currentEpisode = episode; var outputFile = _configProvider.GetValue("iPodConvertDir", ""); var handBrakePreset = _configProvider.GetValue("HandBrakePreset", "iPhone & iPod Touch"); var handBrakeCommand = String.Format("-i \"{0}\" -o \"{1}\" --preset=\"{2}\"", episode.EpisodeFile.Path, outputFile, handBrakePreset); var handBrakeFile = @"C:\Program Files (x86)\Handbrake\HandBrakeCLI.exe"; try { var process = new Process(); process.StartInfo.FileName = handBrakeFile; process.StartInfo.Arguments = handBrakeCommand; process.StartInfo.UseShellExecute = false; process.StartInfo.CreateNoWindow = true; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += new DataReceivedEventHandler(HandBrakeOutputDataReceived); process.Start(); process.BeginOutputReadLine(); process.WaitForExit(); } catch (Exception ex) { Logger.DebugException(ex.Message, ex); return String.Empty; } return outputFile; }
void Run() { if (isRunning) { Debug.LogError("Already Running: " + scriptPath); return; } process_ = new System.Diagnostics.Process(); process_.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; process_.StartInfo.FileName = NodeBinFullPath; process_.StartInfo.Arguments = NodeScriptFullPath + scriptPath; process_.StartInfo.CreateNoWindow = true; process_.StartInfo.RedirectStandardOutput = true; process_.StartInfo.RedirectStandardError = true; process_.StartInfo.UseShellExecute = false; process_.StartInfo.WorkingDirectory = NodeScriptFullPath; process_.OutputDataReceived += OnOutputData; process_.ErrorDataReceived += OnOutputData; process_.EnableRaisingEvents = true; process_.Exited += OnExit; process_.Start(); process_.BeginOutputReadLine(); process_.BeginErrorReadLine(); isRunning = true; }
public String cmd(String cnd) { cnd = cnd.Trim(); String output = " "; Console.WriteLine(cnd); if ((cnd.Substring(0, 3).ToLower() == "cd_") && (cnd.Length > 2)) { if (System.IO.Directory.Exists(cnd.Substring(2).Trim())) cpath = cnd.Substring(2).Trim(); } else { cnd = cnd.Insert(0, "/B /k "); Process p = new Process(); p.StartInfo.CreateNoWindow = true; p.StartInfo.FileName = "cmd.exe"; p.StartInfo.Arguments = cnd; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); p.BeginOutputReadLine(); output = p.StandardOutput.ReadToEnd(); // output of cmd output = (output.Length == 0) ? " " : output; p.WaitForExit(); } return output; // 00 for cmd out put } // end cmd
protected override void OnStart(string[] args) { WriteConfigFile(); process = new Process { StartInfo = { FileName = "metron.exe", Arguments = @"--config=metron\config.json", RedirectStandardOutput = true, RedirectStandardError = true, UseShellExecute = false, WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory } }; process.EnableRaisingEvents = true; process.Exited += process_Exited; var syslog = Syslog.Build(Config.Params(), eventSource); process.OutputDataReceived += (object sender, DataReceivedEventArgs e) => { EventLog.WriteEntry(eventSource, e.Data, EventLogEntryType.Information, 0); if (syslog != null) syslog.Send(e.Data, SyslogSeverity.Informational); }; process.ErrorDataReceived += (object sender, DataReceivedEventArgs e) => { EventLog.WriteEntry(eventSource, e.Data, EventLogEntryType.Warning, 0); if (syslog != null) syslog.Send(e.Data, SyslogSeverity.Warning); }; EventLog.WriteEntry(eventSource, "Starting", EventLogEntryType.Information, 0); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
public string Run(string command) { if (_State == State.Idle) { _Process = new Process(); _Process.StartInfo = new ProcessStartInfo("cmd", "/c " + command) { RedirectStandardOutput = true, RedirectStandardInput = true, RedirectStandardError = true, UseShellExecute = false, CreateNoWindow = false }; _Process.OutputDataReceived += new DataReceivedEventHandler(DataReceived); _Process.Start(); _Process.BeginOutputReadLine(); while(_Process.WaitForInputIdle()) { _State = State.Waiting; } } string output = ""; /* string output = ">>" + command + "\n"; output += _Process.StandardOutput.ReadToEnd(); string error = _Process.StandardError.ReadToEnd(); output += error; output += "\n";*/ _Process.WaitForExit(); _Process.Close(); _State = State.Idle; return output; }
public Tuple<int, string> Execute(string fileName, string arguments) { var process = new Process(); process.StartInfo = new ProcessStartInfo { FileName = fileName, Arguments = arguments, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardOutput = true, RedirectStandardError = true, }; var sb = new StringBuilder(); process.OutputDataReceived += (sender, e) => { sb.AppendLine(e.Data); }; process.ErrorDataReceived += (sender, e) => { sb.AppendLine(e.Data); }; process.Exited += (sender, e) => { }; process.EnableRaisingEvents = true; process.Start(); process.StandardInput.Dispose(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); return Tuple.Create(process.ExitCode, sb.ToString()); }
private Task StartLivestreamer(string inputUrl, DataReceivedEventHandler onData) => Task.Run(() => { Process livestreamer = new Process { StartInfo = { FileName = Config.LivestreamerDir, Arguments = $"--stream-url {inputUrl} best", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }, EnableRaisingEvents = true }; livestreamer.OutputDataReceived += onData; if (!livestreamer.Start()) Logger.FormattedWrite(typeof (TrackData).Name, "Failed starting livestreamer.", ConsoleColor.Red); livestreamer.BeginOutputReadLine(); livestreamer.WaitForExit(); livestreamer.OutputDataReceived -= onData; });
public void run() { var executableName = "starbound_server" + (StarryboundServer.IsMono ? "" : ".exe"); try { ProcessStartInfo startInfo = new ProcessStartInfo(executableName) { WindowStyle = ProcessWindowStyle.Hidden, UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true }; process = Process.Start(startInfo); process.OutputDataReceived += (sender, e) => parseOutput(e.Data); process.BeginOutputReadLine(); process.WaitForExit(); Thread.Sleep(5000); } catch (Exception e) { StarryboundServer.logException("Unable to start starbound_server.exe, is this file in the same directory? " + e.ToString()); StarryboundServer.serverState = Util.ServerState.Crashed; } }
private static void FindProjectReferences() { string appDataPath = Application.dataPath; string output = ""; string selectedAssetPath = AssetDatabase.GetAssetPath(Selection.activeObject); List <string> references = new List <string>(); string guid = AssetDatabase.AssetPathToGUID(selectedAssetPath); var psi = new System.Diagnostics.ProcessStartInfo(); psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized; psi.FileName = "/usr/bin/mdfind"; psi.Arguments = "-onlyin " + Application.dataPath + " " + guid; psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = psi; process.OutputDataReceived += (sender, e) => { if (string.IsNullOrEmpty(e.Data)) { return; } string relativePath = "Assets" + e.Data.Replace(appDataPath, ""); // skip the meta file of whatever we have selected if (relativePath == selectedAssetPath + ".meta") { return; } references.Add(relativePath); }; process.ErrorDataReceived += (sender, e) => { if (string.IsNullOrEmpty(e.Data)) { return; } output += "Error: " + e.Data + "\n"; }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(2000); foreach (var file in references) { output += file + "\n"; Debug.Log(file, AssetDatabase.LoadMainAssetAtPath(file)); } Debug.LogWarning(references.Count + " references found for object " + Selection.activeObject.name + "\n\n" + output); }
// ./Mono/bin/smcs -lib:/opt/UnityBeta/Editor/Data/Managed,Library/ScriptAssemblies -r:UnityEngine.dll,Assembly-CSharp.dll -t:library -out:Mods/sample/ModAssembly.dll Mods/sample/Sources/hmm.cs // Note this is simple compilation (with only own assembly-csharp.dll and unityengine.dll referenced), // if people want to make more advanced mods (include other references) they need to compile them on their own public void Compile(bool overwrite) { if (IsCompiled() && !overwrite) { Debug.Log("Already compiled " + info.name); return; } var sources = GetSources(); string args = ModManager.GetPlatformCompilerArgs(); args += " -t:library -out:\"" + path + "/" + GetAssemblyName() + "\""; foreach (string sourcefile in sources) { args += " \"" + sourcefile + "\""; } UIManager.AutoAddMessage("Executing " + ModManager.GetCompiler() + " " + args); compilerOutput = new List <string>(); var compileProcess = new System.Diagnostics.Process(); compileProcess.StartInfo.FileName = ModManager.GetCompiler(); compileProcess.StartInfo.Arguments = args; // Set UseShellExecute to false for redirection. compileProcess.StartInfo.UseShellExecute = false; // Redirect the standard output of the sort command. // This stream is read asynchronously using an event handler. compileProcess.StartInfo.RedirectStandardOutput = true; compileProcess.StartInfo.RedirectStandardError = true; // Set our event handler to asynchronously read the sort output. compileProcess.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OnCompilerOutput); compileProcess.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(OnCompilerError); // Start the process. compileProcess.Start(); compileProcess.BeginErrorReadLine(); compileProcess.BeginOutputReadLine(); compileProcess.WaitForExit(); lock (compilerOutput){ foreach (var line in compilerOutput) { if (string.IsNullOrEmpty(line)) { return; } UIManager.Instance.AddMessage(line); } } UIManager.Instance.AddMessage("Compiler exited code " + compileProcess.ExitCode); }
public static async Task <string> RunCommandAsync(string filename, string?arguments = null) { var process = new System.Diagnostics.Process(); process.StartInfo.FileName = filename; if (!string.IsNullOrEmpty(arguments)) { process.StartInfo.Arguments = arguments; } process.StartInfo.CreateNoWindow = true; process.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardError = true; process.StartInfo.RedirectStandardOutput = true; var stdOutput = new StringBuilder(); process.OutputDataReceived += (sender, args) => stdOutput.AppendLine(args.Data); // Use AppendLine rather than Append since args.Data is one line of output, not including the newline character. string?stdError = null; try { process.Start(); process.BeginOutputReadLine(); stdError = await process.StandardError.ReadToEndAsync(); await process.WaitForExitAsync(); } catch (Exception e) { throw new Exception("OS error while executing " + Format(filename, arguments) + ": " + e.Message, e); } if (process.ExitCode == 0) { return(stdOutput.ToString()); } else { var message = new StringBuilder(); if (!string.IsNullOrEmpty(stdError)) { message.AppendLine(stdError); } if (stdOutput.Length != 0) { message.AppendLine("Std output:"); message.AppendLine(stdOutput.ToString()); } throw new Exception(Format(filename, arguments) + " finished with exit code = " + process.ExitCode + ": " + message); } }
private static void LogCount0PathReferences(string assetPath) { string appDataPath = Application.dataPath; string output = ""; string selectedAssetPath = assetPath; List <string> references = new List <string>(); string guid = AssetDatabase.AssetPathToGUID(selectedAssetPath); var psi = new System.Diagnostics.ProcessStartInfo(); psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized; psi.FileName = "/usr/bin/mdfind"; psi.Arguments = "-onlyin " + Application.dataPath + " " + guid; psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = psi; process.OutputDataReceived += (sender, e) => { if (string.IsNullOrEmpty(e.Data)) { return; } string relativePath = "Assets" + e.Data.Replace(appDataPath, ""); if (relativePath == selectedAssetPath + ".meta") { return; } references.Add(relativePath); }; process.ErrorDataReceived += (sender, e) => { if (string.IsNullOrEmpty(e.Data)) { return; } output += "Error: " + e.Data + "\n"; }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); // process.WaitForExit(2000); process.WaitForExit(); if (references.Count == 0) { Debug.LogError("count = " + references.Count + " path = " + assetPath); } }
public static void Compile(string exe, string prmt) { //bool finished = false; var process = new System.Diagnostics.Process(); //var processing = 0f; try { var pi = new System.Diagnostics.ProcessStartInfo(exe, prmt); pi.WorkingDirectory = "."; pi.RedirectStandardInput = false; pi.RedirectStandardOutput = true; pi.RedirectStandardError = true; pi.UseShellExecute = false; pi.CreateNoWindow = true; process.OutputDataReceived += (sender, e) => { if (string.IsNullOrEmpty(e.Data)) { return; } UnityEngine.Debug.Log(e.Data); }; process.ErrorDataReceived += (sender, e) => { if (!string.IsNullOrEmpty(e.Data)) { UnityEngine.Debug.LogError(e.GetType() + ": " + e.Data); } }; process.Exited += (sender, e) => { UnityEngine.Debug.Log($"{exe} {prmt} Exit"); }; process.StartInfo = pi; process.EnableRaisingEvents = true; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); } catch (System.Exception e) { UnityEngine.Debug.LogError("catch: " + e); } // UnityEngine.Debug.Log("finished: " + process.ExitCode); EditorUtility.ClearProgressBar(); }
protected void Start() { process = new System.Diagnostics.Process(); process.StartInfo.FileName = Application.dataPath + "/../openvr-tracking.exe"; process.StartInfo.Arguments = refreshPeriod.ToString(); process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardInput = true; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += ProcessDataReceived; process.Start(); process.BeginOutputReadLine(); }
// Use this for initialization void Awake() { string file = System.IO.Directory.GetCurrentDirectory() + @"\Execute\BReceiverConsole.exe"; // Debug.Log(file); proc = new System.Diagnostics.Process(); string applicationName = "BReceiverConsole"; foreach (var p in System.Diagnostics.Process.GetProcessesByName(applicationName)) { if (p.ProcessName.Equals(applicationName)) { p.Kill(); } } proc.EnableRaisingEvents = true; proc.StartInfo.FileName = file; proc.StartInfo.RedirectStandardInput = true; proc.StartInfo.RedirectStandardOutput = true; // proc.StartInfo.RedirectStandardError = true; proc.StartInfo.UseShellExecute = false; proc.OutputDataReceived += onDataReceive; //proc.ErrorDataReceived += onDataReceive; if (ConsoleHide) { proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; proc.StartInfo.CreateNoWindow = true; } else { proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal; proc.StartInfo.CreateNoWindow = false; } //proc.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; //proc.StartInfo.CreateNoWindow = true; proc.Start(); // Debug.Log("proc Started"); proc.BeginOutputReadLine(); // Debug.Log("proc BeginOutputReadLine"); }
void Start() { Screen.fullScreen = !Screen.fullScreen; i = 0; m_Path = Application.dataPath; //Output the Game data path to the console //Debug.Log("Path : " + m_Path); /*p = new System.Diagnostics.Process(); * p.StartInfo.FileName = m_Path + "/pythontest.py"; * p.StartInfo.Arguments = "optional arguments separated with spaces"; * p.StartInfo.UseShellExecute = false; * p.StartInfo.RedirectStandardOutput = true; * p.StartInfo.RedirectStandardError = true; * p.Start(); */ Debug.Log("Start read"); p = new System.Diagnostics.Process(); p.StartInfo.RedirectStandardError = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; //p.StartInfo.CreateNoWindow = true; //p.EnableRaisingEvents = true; //p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.FileName = m_Path + "/webcam-pulse-detector-no_openmdao/get_pulse.py"; //p.StartInfo.FileName = m_Path + "/pythontest.py"; //p.StartInfo.Arguments = "optional arguments separated with spaces"; p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler( (s, e) => { Debug.Log("DATA: " + i + " - " + e.Data); Debug.Log(s); } ); p.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler( (s, e) => { Debug.Log("ERROR:" + i + " - " + e.Data); } ); p.Start(); p.BeginOutputReadLine(); Debug.Log("Read end"); }
public static void ProcessCommandEx(string command, string argument) { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = command; process.StartInfo.Arguments = argument; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OnOutputDataReceived); process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(OnErrorDataReceived); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(); }
private static List <string> FindProjectReferences(string searchString) { string appDataPath = Application.dataPath; List <string> references = new List <string>(); var psi = new System.Diagnostics.ProcessStartInfo(); psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Maximized; psi.FileName = "/usr/bin/mdfind"; psi.Arguments = "-onlyin " + Application.dataPath + " " + searchString; psi.UseShellExecute = false; psi.RedirectStandardOutput = true; psi.RedirectStandardError = true; System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo = psi; process.OutputDataReceived += (sender, e) => { if (string.IsNullOrEmpty(e.Data)) { return; } string relativePath = "Assets" + e.Data.Replace(appDataPath, ""); if (!references.Contains(relativePath)) { references.Add(relativePath); } }; process.ErrorDataReceived += (sender, e) => { if (string.IsNullOrEmpty(e.Data)) { return; } Debug.LogError(e.Data); }; process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); process.WaitForExit(10000); return(references); }
private void TwitterProcessStart() { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = "node"; process.StartInfo.Arguments = "twitter.js ハウステンボスの思い出"; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputHandler); process.StartInfo.RedirectStandardError = true; process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorOutputHanlder); process.StartInfo.RedirectStandardInput = false; process.StartInfo.CreateNoWindow = true; process.EnableRaisingEvents = true; process.Exited += new System.EventHandler(Process_Exit_Twitter); process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
void RunCommand() { process = new System.Diagnostics.Process(); process.StartInfo.FileName = "cmd.exe"; process.StartInfo.Arguments = "/c " + npmCommand + " " + port; // Note the /c command (*) process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.StartInfo.CreateNoWindow = true; process.StartInfo.WorkingDirectory = directoryPath; //* Set your output and error (asynchronous) handlers process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputHandler); process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputHandler); //* Start process and handlers process.Start(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); }
public static void RunPythonScript() { System.Diagnostics.Process p = new System.Diagnostics.Process(); //string path = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "/../test.py";// 获得python文件的绝对路径(将文件放在c#的debug文件夹中可以这样操作) string path = Application.dataPath + "/../bat/test.py";//(因为我没放debug下,所以直接写的绝对路径,替换掉上面的路径了) GameLogger.LogGreen("path = " + path); p.StartInfo.FileName = "python";//没有配环境变量的话,可以像我这样写python.exe的绝对路径。如果配了,直接写"python.exe"即可 string sArguments = path; p.StartInfo.Arguments = sArguments; p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardError = true; p.StartInfo.CreateNoWindow = true; p.Start(); p.BeginOutputReadLine(); p.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(p_OutputDataReceived); //GameLogger.LogGreen("consolue output = " + Console.ReadLine()); p.WaitForExit(); }
public static bool Build() { FixChartJsBlazorMap(); int exitCode; using (System.Diagnostics.Process pProcess = new System.Diagnostics.Process()) { pProcess.StartInfo.WorkingDirectory = "../sc2dsstats.app"; pProcess.StartInfo.FileName = "electronize"; pProcess.StartInfo.Arguments = "build /target win /package-json ./package.json /electron-params --publish=always /p:PublishSingleFile=false"; pProcess.StartInfo.UseShellExecute = false; pProcess.StartInfo.RedirectStandardOutput = true; pProcess.StartInfo.RedirectStandardError = true; pProcess.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; pProcess.StartInfo.CreateNoWindow = true; pProcess.OutputDataReceived += (sender, args) => { Program.logger?.LogInformation(args.Data); }; pProcess.ErrorDataReceived += (sender, args) => { Program.logger?.LogError(args.Data); }; pProcess.Start(); pProcess.BeginOutputReadLine(); pProcess.BeginErrorReadLine(); // string output = pProcess.StandardOutput.ReadToEnd(); pProcess.WaitForExit(); pProcess.CancelOutputRead(); pProcess.CancelErrorRead(); exitCode = pProcess.ExitCode; } if (exitCode == 0) { Program.logger?.LogInformation($"Electronize finished with ExitCode {exitCode}"); return(true); } else { Program.logger?.LogError($"Electronize failed with ExitCode {exitCode}"); return(false); } }
static bool Exec(string filename, string args) { System.Diagnostics.Process process = new System.Diagnostics.Process(); process.StartInfo.FileName = filename; process.StartInfo.Arguments = args; int exit_code = -1; try { process.Start(); if (process.StartInfo.RedirectStandardOutput && process.StartInfo.RedirectStandardError) { process.BeginOutputReadLine(); Debug.LogError(process.StandardError.ReadToEnd()); } else if (process.StartInfo.RedirectStandardOutput) { string data = process.StandardOutput.ReadToEnd(); Debug.Log(data); } else if (process.StartInfo.RedirectStandardError) { string data = process.StandardError.ReadToEnd(); Debug.LogError(data); } } catch (Exception e) { Debug.LogException(e); return(false); } process.WaitForExit(); exit_code = process.ExitCode; process.Close(); return(exit_code == 0); }
private void StartProcess() { if (scriptName == "") { //TODO: if no script provided, should redirect the input, & listen to user/app input! // print("No script name provided!"); //TODO: use other exception type? throw new System.Exception("No script name provided!"); } process_ = new System.Diagnostics.Process(); process_.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; process_.StartInfo.FileName = System.IO.Path.Combine(nodeFullPath, NODE_BIN); process_.StartInfo.Arguments = System.IO.Path.Combine(scriptFullPath, scriptName) + " " + scriptArguments; process_.StartInfo.CreateNoWindow = true; process_.StartInfo.RedirectStandardOutput = true; process_.StartInfo.RedirectStandardError = true; process_.StartInfo.UseShellExecute = false; process_.StartInfo.WorkingDirectory = scriptFullPath; if (useCommunication) { process_.OutputDataReceived += OnOutputData; process_.ErrorDataReceived += OnErrorData; } process_.EnableRaisingEvents = true; process_.Exited += OnExit; //TODO: remove - debug purpose print("Starting: " + process_.StartInfo.FileName + " " + process_.StartInfo.Arguments); process_.Start(); process_.BeginOutputReadLine(); process_.BeginErrorReadLine(); }
public static bool ejecutar(String argumento, String rutaArchivo, Label etiquetaMensajes, ProgressBar barraDeProgreso) { String rutaFFMPEG = ConfigurationManager.AppSettings["rutaFFMPEG"].ToString(); String rutaEXIF = ConfigurationManager.AppSettings["rutaEXIF"].ToString(); String[] frame; int frameActual = 0; int frameTotal = 0; Boolean terminamos = false; int contadorEstupido = 0; Process procprobe = new System.Diagnostics.Process(); procprobe.StartInfo.FileName = rutaEXIF; procprobe.EnableRaisingEvents = true; procprobe.StartInfo.CreateNoWindow = true; procprobe.StartInfo.Domain = ""; procprobe.StartInfo.LoadUserProfile = false; procprobe.StartInfo.Password = null; procprobe.StartInfo.RedirectStandardError = true; procprobe.StartInfo.RedirectStandardOutput = true; procprobe.StartInfo.StandardErrorEncoding = null; procprobe.StartInfo.StandardOutputEncoding = null; procprobe.StartInfo.UserName = ""; procprobe.StartInfo.UseShellExecute = false; procprobe.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; procprobe.StartInfo.WorkingDirectory = "C:\\LOGOS\\TRABAJOS"; // procprobe.StartInfo.Arguments = "-v error -count_frames -select_streams v:0 -show_entries stream=nb_read_frames -of default=nokey=1:noprint_wrappers=1 \"" + rutaArchivo + "\""; procprobe.StartInfo.Arguments = "-MediaDuration \"" + rutaArchivo + "\""; Console.WriteLine(procprobe.StartInfo.Arguments); procprobe.OutputDataReceived += new DataReceivedEventHandler( (s, e) => { if (frameTotal == 0) { try { String[] duracion_raw = e.Data.Substring(34).Split(':'); int fps = Tramite.obtenerFPS(rutaArchivo); Console.WriteLine("#### que corno es el tiempo"); Console.WriteLine(duracion_raw[0]); Console.WriteLine(duracion_raw[1]); Console.WriteLine(duracion_raw[2]); int segundos = Int32.Parse(duracion_raw[0]) * 3600 + Int32.Parse(duracion_raw[1]) * 60 + Int32.Parse(duracion_raw[2]); frameTotal = segundos * fps + 1; Console.WriteLine("##### El frametotal es: " + frameTotal.ToString()); } catch (Exception) { Console.WriteLine("Algun error impidió revisar la metadata"); } } } ); procprobe.Start(); procprobe.BeginOutputReadLine(); // procprobe.BeginErrorReadLine(); procprobe.WaitForExit(); procprobe.Close(); procprobe.Dispose(); Process procesador = new System.Diagnostics.Process(); procesador.StartInfo.FileName = rutaFFMPEG; procesador.StartInfo.Arguments = argumento; procesador.EnableRaisingEvents = true; procesador.StartInfo.CreateNoWindow = true; procesador.StartInfo.Domain = ""; procesador.StartInfo.LoadUserProfile = false; procesador.StartInfo.Password = null; procesador.StartInfo.RedirectStandardError = true; procesador.StartInfo.RedirectStandardOutput = true; procesador.StartInfo.StandardErrorEncoding = null; procesador.StartInfo.StandardOutputEncoding = null; procesador.StartInfo.UserName = ""; procesador.StartInfo.UseShellExecute = false; procesador.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; procesador.StartInfo.WorkingDirectory = "C:\\LOGOS\\TRABAJOS"; procesador.OutputDataReceived += new DataReceivedEventHandler( (s, a) => { etiquetaMensajes.Text = a.Data; Console.WriteLine(a.Data); if (a.Data != null) { if (a.Data.ToString().Length > 6) { if (a.Data.Substring(0, 5) == "frame=") { frame = a.Data.Split('='); try { frameActual = Int32.Parse(frame[1].Substring(0, frame[1].Length - 3)); barraDeProgreso.Value = frameActual * 100 / frameTotal; } catch (Exception) { // Console.WriteLine("No se pudo obtener el frame actual"); } } } } } ); procesador.ErrorDataReceived += new DataReceivedEventHandler( (s, a) => { etiquetaMensajes.Text = a.Data; // Console.WriteLine(a.Data); try { frame = a.Data.Split('='); frameActual = Int32.Parse(frame[1].Substring(0, frame[1].Length - 3)); barraDeProgreso.Value = frameActual * 100 / frameTotal; } catch (Exception) { // Console.WriteLine("No se pudo obtener el frame actual"); } } ); procesador.Start(); procesador.BeginOutputReadLine(); procesador.BeginErrorReadLine(); procesador.WaitForExit(); procesador.Close(); procesador.Dispose(); return(true); // Console.WriteLine(rutaFFMPEG + " " + argumento); }
private void sliceToCreateGcode(string stlFilePath, string configJsonFilePath, string gcodeFilePath) { Debug.Log("sliceToCreateGcode..." + "\n"); _infoStruct.isSlicing = true; _infoStruct.progress = 0.0f; _infoStruct.isCurGcodeCreateBeanAvailable = false; curGcodeBean = new GcodeCreateBean(stlFilePath, configJsonFilePath, gcodeFilePath); //2.new process to call shell: use CuraEngine to slice and create g-code System.Diagnostics.Process process = new System.Diagnostics.Process(); string shellPath = null; string CuraEnginePath = null; //Attention: mac and win, Arguments and FileName are different //In shell/bat : CuraEnginePath="$1" configPath="$2" gcodePath="$3" stlPath="$4" switch (Global.GetInstance().GetOSPlatform()) { case Global.OS_Platform_Enum.Mac: shellPath = PathManager.shellPath_createGcode_mac(); CuraEnginePath = PathManager.enginePath_mac(); process.StartInfo.FileName = "/bin/sh"; process.StartInfo.Arguments = "\"" + shellPath + "\"" + " " + "\"" + CuraEnginePath + "\"" + " " + "\"" + configJsonFilePath + "\"" + " " + "\"" + gcodeFilePath + "\"" + " " + "\"" + stlFilePath + "\""; break; case Global.OS_Platform_Enum.Win_64: shellPath = PathManager.shellPath_createGcode_win(); CuraEnginePath = PathManager.enginePath_win64(); process.StartInfo.FileName = shellPath; process.StartInfo.Arguments = "\"" + CuraEnginePath + "\"" + " " + "\"" + configJsonFilePath + "\"" + " " + "\"" + gcodeFilePath + "\"" + " " + "\"" + stlFilePath + "\""; break; case Global.OS_Platform_Enum.Win_32: shellPath = PathManager.shellPath_createGcode_win(); CuraEnginePath = PathManager.enginePath_win32(); process.StartInfo.FileName = shellPath; process.StartInfo.Arguments = "\"" + CuraEnginePath + "\"" + " " + "\"" + configJsonFilePath + "\"" + " " + "\"" + gcodeFilePath + "\"" + " " + "\"" + stlFilePath + "\""; break; } Debug.Log("process FileName:" + process.StartInfo.FileName + "\n"); Debug.Log("process Arguments :" + process.StartInfo.Arguments.Replace(" ", "\n") + "\n"); process.StartInfo.CreateNoWindow = true; process.StartInfo.UseShellExecute = false; process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler((sender, e) => { if (!System.String.IsNullOrEmpty(e.Data)) { string outputStr = e.Data.Trim(); // Debug.Log (outputStr + "\n"); if (outputStr.StartsWith("Progress:inset+skin:") || outputStr.StartsWith("Progress:export:")) { if (outputStr.EndsWith("%")) { _infoStruct.progress = float.Parse(outputStr.Substring(outputStr.Length - 9, 8)); //not include % } } else if (outputStr.StartsWith(";Filament used:")) { //Filament is either in mm3 or mm (depending on your g-code flavour. Reprap uses mm, ultiCode uses mm3) curGcodeBean.filamentLength = float.Parse(outputStr.Split(':') [1].Replace("m", "").Trim()); curGcodeBean.filamentWeight = Mathf.PI * (1.75f / 2) * (1.75f / 2) * curGcodeBean.filamentLength * 1.24f; } else if (outputStr.StartsWith("Print time:")) { //add empirical parameter : 1.07 curGcodeBean.printTime = (int)(int.Parse(outputStr.Split(':') [1].Trim()) * 1.07f); } } }); process.EnableRaisingEvents = true; //3.slice finish process.Exited += (sender, e) => { Debug.Log("Slice process exited" + "\n"); _infoStruct.progress = 1.0F; _infoStruct.isSlicing = false; _infoStruct.isCurGcodeCreateBeanAvailable = true; foreach (Listener listener in _listenerList) { listener.OnGcodeCreated(curGcodeBean); } }; process.Start(); process.BeginOutputReadLine(); }
public static int obtenerFPS(String rutaArchivo) { String rutaEXIF = ConfigurationManager.AppSettings["rutaEXIF"].ToString(); Process borrador = new System.Diagnostics.Process(); int framerate = 0; borrador.StartInfo.FileName = rutaEXIF; borrador.EnableRaisingEvents = true; borrador.StartInfo.CreateNoWindow = true; borrador.StartInfo.Domain = ""; borrador.StartInfo.LoadUserProfile = false; borrador.StartInfo.Password = null; borrador.StartInfo.RedirectStandardError = true; borrador.StartInfo.RedirectStandardOutput = true; borrador.StartInfo.StandardErrorEncoding = null; borrador.StartInfo.StandardOutputEncoding = null; borrador.StartInfo.UserName = ""; borrador.StartInfo.UseShellExecute = false; borrador.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; borrador.StartInfo.WorkingDirectory = "C:\\LOGOS\\TRABAJOS"; borrador.StartInfo.Arguments = "-VideoFrameRate \"" + rutaArchivo + "\""; Console.WriteLine(borrador.StartInfo.Arguments); borrador.OutputDataReceived += new DataReceivedEventHandler( (s, e) => { if (framerate == 0) { try { framerate = Int32.Parse(e.Data.Substring(34)); } catch (Exception) { Console.WriteLine("No se pudo obtener el frame rate" + e.Data); } } }); borrador.ErrorDataReceived += new DataReceivedEventHandler( (s, e) => { if (framerate == 0) { try { framerate = Int32.Parse(e.Data.Substring(34)); } catch (Exception) { Console.WriteLine("No se pudo obtener el frame rate" + e.Data); } } }); borrador.Start(); borrador.BeginOutputReadLine(); borrador.BeginErrorReadLine(); borrador.WaitForExit(); borrador.Close(); borrador.Dispose(); return(framerate); }
public static int duracion(string rutaArchivo) { string respuesta = ""; string rutaMEDIAINFO = ConfigurationManager.AppSettings["rutaMEDIAINFO"].ToString(); Process borrador = new System.Diagnostics.Process(); borrador.StartInfo.FileName = rutaMEDIAINFO; borrador.EnableRaisingEvents = false; borrador.StartInfo.CreateNoWindow = true; borrador.StartInfo.Domain = ""; borrador.StartInfo.LoadUserProfile = false; borrador.StartInfo.Password = null; borrador.StartInfo.RedirectStandardError = true; borrador.StartInfo.RedirectStandardOutput = true; borrador.StartInfo.StandardErrorEncoding = null; borrador.StartInfo.StandardOutputEncoding = null; borrador.StartInfo.UserName = ""; borrador.StartInfo.UseShellExecute = false; borrador.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; borrador.StartInfo.WorkingDirectory = "C:\\LOGOS\\TRABAJOS"; borrador.StartInfo.Arguments = "--Output=\"Video;%Duration%\" \"" + rutaArchivo + "\""; Console.WriteLine(borrador.StartInfo.Arguments); borrador.OutputDataReceived += new DataReceivedEventHandler( (s, e) => { try { respuesta = e.Data.ToString(); } catch (Exception) { Console.WriteLine("No se pudo obtener el tipo de escaneo de campo [NADA]"); } }); borrador.ErrorDataReceived += new DataReceivedEventHandler( (s, e) => { try { respuesta = e.Data.ToString(); } catch (Exception) { // Console.WriteLine("No se pudo obtener el tipo de escaneo de campo [" + e.Data + "]"); } }); borrador.Start(); borrador.BeginOutputReadLine(); //borrador.BeginErrorReadLine(); borrador.WaitForExit(); borrador.Close(); borrador.Dispose(); return(Int32.Parse(respuesta)); }
public static int RunProcessWithInput(string cmd, string args, string input) { ProcessStartInfo startInfo = new ProcessStartInfo { FileName = cmd, Arguments = ""+args, UseShellExecute = false, RedirectStandardInput = true, RedirectStandardError = true, RedirectStandardOutput = true, }; using (Process process = new Process()) { process.EnableRaisingEvents = true; process.StartInfo = startInfo; process.Start(); process.OutputDataReceived += (sender, e) => { if (e.Data != null) log.Info(e.Data); }; process.ErrorDataReceived += (sender, e) => { if (e.Data != null) log.Error(e.Data); }; AutoResetEvent are = new AutoResetEvent(false); process.Exited += (sender, e) => { Thread.Sleep(1000); are.Set(); log.Info("Process exited"); }; process.Start(); using (StreamReader reader = new StreamReader(new FileStream(input, FileMode.Open))) { string line; while ((line = reader.ReadLine()) != null) process.StandardInput.WriteLine(line); } process.StandardInput.Close(); process.BeginOutputReadLine(); process.BeginErrorReadLine(); //NOTE: Looks like we have a mono bug: https://bugzilla.xamarin.com/show_bug.cgi?id=6291 //have a wait time for now. are.WaitOne(10 * 1000); if (process.HasExited) return process.ExitCode; else //WTF? Should have exited dammit! { process.Kill(); return 1; } } }
/// <summary> /// Executes process with output and erroroutput /// </summary> /// <param name="processName"></param> /// <param name="commandLineArguments"></param> /// <param name="returnCode"></param> /// <param name="waitToExit"></param> /// <param name="output"></param> /// <param name="errorOutput"></param> public static void LaunchForErrorandOutputArgs(string processName, string commandLineArguments, ref int returnCode, bool waitToExit, ref string output, ref string errorOutput) { //if (!File.Exists(processName)) // throw new Exception(processName + " does not exist"); string outputVal = ""; string errorVal = ""; try { returnCode = 0; output = ""; errorOutput = ""; using (System.Diagnostics.Process proc = new System.Diagnostics.Process()) { System.Diagnostics.ProcessStartInfo sInfo = new System.Diagnostics.ProcessStartInfo(); sInfo.FileName = processName; if (commandLineArguments == null) { commandLineArguments = ""; } sInfo.Arguments = commandLineArguments; sInfo.UseShellExecute = false; sInfo.RedirectStandardError = true; sInfo.RedirectStandardOutput = true; sInfo.CreateNoWindow = true; proc.StartInfo = sInfo; //output = DateTime.Now + " : Process " + sInfo.FileName + " started with arguments " + sInfo.Arguments + Environment.NewLine; proc.OutputDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { outputVal += e.Data; } ); proc.ErrorDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { errorVal += e.Data; } ); proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); if (waitToExit) { proc.WaitForExit(); returnCode = proc.ExitCode; } //proc.Close(); //proc.Dispose(); } } catch { returnCode = 256; throw; } finally { output = outputVal; errorOutput = errorVal; } }
// プロセスの開始. private static void Process_Start() { // プロセス作成. System.Diagnostics.Process process = new System.Diagnostics.Process(); // プロセス起動にシェルを使用するかどうか. process.StartInfo.UseShellExecute = false; // 入力を可能にする. process.StartInfo.RedirectStandardInput = true; // 出力を読み取り可能にする. process.StartInfo.RedirectStandardOutput = true; // プロセス出力イベント設定. process.OutputDataReceived += new System.Diagnostics.DataReceivedEventHandler(OutputHandler); // エラー出力読み取り可. process.StartInfo.RedirectStandardError = true; // エラー出力イベント設定. process.ErrorDataReceived += new System.Diagnostics.DataReceivedEventHandler(ErrorOutputHanlder); // 作業ディレクトリにプロジェクトのルートパスを指定. process.StartInfo.WorkingDirectory = m_parentPath; // svnコマンドを実行. #if UNITY_EDITOR_WIN process.StartInfo.FileName = System.Environment.ExpandEnvironmentVariables("svn"); #endif #if UNITY_EDITOR_OS process.StartInfo.FileName = SVN_COMMAND; #endif // 新しいウインドウを作成しない. process.StartInfo.CreateNoWindow = true; string command = null; // コマンドの指定. switch (m_State) { case State.None: command = null; break; case State.Log: command = LOG_COMMAND + " " + m_commandJoin; break; case State.Status: command = STATUS_COMMAND + " " + m_commandJoin; break; case State.Update: command = UPDATE_COMMAND + " " + m_commandJoin; break; case State.Revert: command = REVERT_COMMAND + " " + m_commandJoin; break; case State.Add: command = ADD_COMMAND + " " + m_commandJoin; break; case State.Commit: if (!string.IsNullOrEmpty(m_commitMessage)) { command = COMMIT_COMMAND + " " + m_commandJoin + " " + COMMIT_MESSAGE_COMMAND + " " + m_commitMessage; } break; } if (command != null) { // コマンドとパスを引数に. process.StartInfo.Arguments = command; // プロセス終了時にExitedイベントを発生. process.EnableRaisingEvents = true; // プロセス終了時に呼び出されるイベントの設定. process.Exited += new System.EventHandler(Process_Exit); // プロセススタート. process.Start(); Debug.Log("---------------------------------- Process Start ----------------------------------"); // プロセス結果出力. process.BeginOutputReadLine(); // プロセスエラー結果出力. process.BeginErrorReadLine(); } }
/// <summary> /// Launches the passed process /// </summary> /// <param name="processName">pass process name</param> /// <param name="commandLineArguments">pass command line argument</param> /// <returns></returns> public static string Launch(string processName, string commandLineArguments, ref int returnCode, bool waitToExit) { //if (!File.Exists(processName)) // throw new Exception(processName + " does not exist"); try { returnCode = 0; string output = ""; string errorOutput = ""; using (System.Diagnostics.Process proc = new System.Diagnostics.Process()) { System.Diagnostics.ProcessStartInfo sInfo = new System.Diagnostics.ProcessStartInfo(); sInfo.FileName = processName; if (commandLineArguments == null) { commandLineArguments = ""; } sInfo.Arguments = commandLineArguments; sInfo.UseShellExecute = false; sInfo.RedirectStandardError = true; sInfo.RedirectStandardOutput = true; sInfo.CreateNoWindow = true; proc.StartInfo = sInfo; output = DateTime.Now + " : Process " + sInfo.FileName + " started with arguments " + sInfo.Arguments + Environment.NewLine; output += " **********Output Log******** " + Environment.NewLine; errorOutput += " **********Error Log******** " + Environment.NewLine; proc.OutputDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { output += DateTime.Now + " : " + e.Data + Environment.NewLine; } } ); proc.ErrorDataReceived += new DataReceivedEventHandler ( delegate(object sender, DataReceivedEventArgs e) { if (!string.IsNullOrEmpty(e.Data)) { errorOutput += DateTime.Now + " : " + e.Data + Environment.NewLine; } } ); proc.Start(); proc.BeginOutputReadLine(); proc.BeginErrorReadLine(); if (waitToExit) { proc.WaitForExit(); returnCode = proc.ExitCode; } //proc.Close(); //proc.Dispose(); } if (returnCode != 0) { return(output + Environment.NewLine + errorOutput); } else { return(output); } } catch// (Exception ex) { returnCode = 255; //return ("Failed to launch process " + ex.Message); throw; } }
private void GetSamplesFromModel(Vector3 center, Vector3 normal, Vector3 direction) { Debug.Log("Start generator"); foreach (var go in samples) { GameObject.Destroy(go); } samples.Clear(); var coefficients = surface.Coefficients.ToArray(); var normalToZ = new Frame(normal); var zToDirection = new Frame(-direction).Invert(); TestDataGenerator.RotatePolynomial(coefficients, normalToZ.x, normalToZ.y, normalToZ.z); if (!incidentIsNormal) { TestDataGenerator.RotatePolynomial(coefficients, zToDirection.x, zToDirection.y, zToDirection.z); } string[] arguments = null; string fileExe = null; var model = string.IsNullOrWhiteSpace(modelVersion) ? $"{modelName}/final" : $"{modelName}/{modelVersion}"; switch (sampleSource) { case SampleSource.Cpp: fileExe = @"D:\Bachelorarbeit\CppModelTest\x64\Release\CppModelTest.exe"; arguments = new string[] { model, samplesToGenerate.ToString(), modelStddev.ToString(), $"{string.Join(",", coefficients)},{surface.alphaEff},{surface.g},{surface.ior}" }; break; case SampleSource.Python: fileExe = "python.exe"; arguments = new string[] { @"D:\Bachelorarbeit\Bachelorarbeit\Model\generate_samples.py", model, samplesToGenerate.ToString(), modelStddev.ToString(), $"{string.Join(",", coefficients)},{surface.alphaEff},{surface.g},{surface.ior}" }; break; default: fileExe = @"D:\Bachelorarbeit\CppModelTest\x64\Release\CppModelTest.exe"; arguments = new string[] { model, samplesToGenerate.ToString(), modelStddev.ToString(), $"{string.Join(",", coefficients)},{surface.alphaEff},{surface.g},{surface.ior}" }; break; } var p = new System.Diagnostics.Process(); p.StartInfo.FileName = fileExe; p.StartInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; p.StartInfo.WorkingDirectory = @"D:\Bachelorarbeit\Bachelorarbeit\Model"; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.Arguments = string.Join(" ", arguments.Select(a => $"\"{a}\"")); Debug.Log(p.StartInfo.Arguments); var r = new System.Random(); p.OutputDataReceived += (sender, args) => { if (args.Data != null && args.Data.StartsWith("# ")) { var parts = args.Data.Substring(2).Split(',').Select(s => float.Parse(s)).ToArray(); var pos = new Vector3(parts[0], parts[1], parts[2]); var n = PolySurface.GetNormalAt(coefficients, pos, Vector3.zero); //pos = new Vector3(0, 0, (float)r.NextDouble()); if (!incidentIsNormal) { pos = zToDirection.ToMatrix() * pos; n = zToDirection.ToMatrix() * n; } pos = normalToZ.ToMatrix() * pos; n = normalToZ.ToMatrix() * n; pos += center; samplesTemp.Add(new MeshDBSample { position = pos, gradient = n }); } }; p.Start(); p.BeginOutputReadLine(); process = p; }
private void startAnalyzerProcess(string analyzerExePath, string arguments) { System.Diagnostics.Process process = null; try { Debug.Assert(!String.IsNullOrEmpty(analyzerExePath)); Debug.Assert(!String.IsNullOrEmpty(arguments)); process = new System.Diagnostics.Process(); process.StartInfo.FileName = analyzerExePath; process.StartInfo.WorkingDirectory = Path.GetDirectoryName(analyzerExePath); process.StartInfo.Arguments = arguments; process.StartInfo.CreateNoWindow = true; // Set UseShellExecute to false for output redirection. process.StartInfo.UseShellExecute = false; // Redirect the standard output of the command. process.StartInfo.RedirectStandardOutput = true; process.StartInfo.RedirectStandardError = true; // Set our event handler to asynchronously read the sort output. process.OutputDataReceived += new DataReceivedEventHandler(this.analyzerOutputHandler); process.ErrorDataReceived += new DataReceivedEventHandler(this.analyzerOutputHandler); _ = CPPCheckPluginPackage.AddTextToOutputWindowAsync("Starting analyzer with arguments: " + arguments + "\n"); var timer = Stopwatch.StartNew(); // Start the process. process.Start(); try { process.PriorityClass = ProcessPriorityClass.Idle; } catch (System.InvalidOperationException) { } onProgressUpdated(0); // Start the asynchronous read of the sort output stream. process.BeginOutputReadLine(); process.BeginErrorReadLine(); // Wait for analysis completion while (!process.WaitForExit(500)) { if (_terminateThread) { // finally block will run anyway and do the cleanup return; } } timer.Stop(); analysisFinished(arguments); if (process.ExitCode != 0) { _ = CPPCheckPluginPackage.AddTextToOutputWindowAsync(analyzerExePath + " has exited with code " + process.ExitCode.ToString() + "\n"); } else { double timeElapsed = Math.Round(timer.Elapsed.TotalSeconds, 3); _ = CPPCheckPluginPackage.AddTextToOutputWindowAsync("Analysis completed in " + timeElapsed.ToString() + " seconds\n"); } process.Close(); process = null; } catch (Exception ex) { DebugTracer.Trace(ex); } finally { onProgressUpdated(100); if (process != null) { try { process.Kill(); } catch (Exception ex) { DebugTracer.Trace(ex); } process.Dispose(); } } }