/// <summary> /// 当接收到标准输出或标准错误时调用 /// </summary> /// <param name="e"></param> protected virtual void OnOutputReceived(OutputReceivedEventArgs e) { Task.Run(() => { OutputReceived?.Invoke(this, e); }); }
/// <summary> /// To be called by view when ready /// </summary> public async Task <TerminalResponse> StartShellProcessAsync(ShellProfile shellProfile, TerminalSize size, SessionType sessionType, string termState) { if (!_requireShellProcessStart && !string.IsNullOrEmpty(termState)) { OutputReceived?.Invoke(this, Encoding.UTF8.GetBytes(termState)); } _trayProcessCommunicationService.SubscribeForTerminalOutput(Id, t => OutputReceived?.Invoke(this, t)); if (_requireShellProcessStart) { var response = await _trayProcessCommunicationService .CreateTerminalAsync(Id, size, shellProfile, sessionType).ConfigureAwait(false); if (response.Success) { _fallbackTitle = response.Name; SetTitle(_fallbackTitle); } return(response); } else { return(await _trayProcessCommunicationService.PauseTerminalOutputAsync(Id, false)); } }
/// <summary> /// 处理并触发OutputReceived事件时发生 /// </summary> /// <param name="src"></param> /// <param name="isError"></param> private void RaiseOutputReceived(DataReceivedEventArgs src, bool isError = false) { if (src.Data == null) { return; } if (src.Data == "") { return; } var match = Regex.Match(src.Data, exitCodePattern); if (match.Success) { leastShellExitCode = int.Parse(match.Result("${code}")); return; } if (!isError) { _builder.AppendOut(src.Data); } else { _builder.AppendError(src.Data); } OutputReceived?.Invoke(this, new OutputReceivedEventArgs(src, isError)); }
protected virtual void OnOutputReceived(byte[] output) { OutputReceived?.Invoke(this, new OutputReceivedArgs() { data = output }); }
public void WriteOutput(string jobId, string output) { jobId = rgxUrl.Replace(jobId, ""); output = rgxPwd.Replace(output, (m) => m.Groups[1] + " ****"); OutputReceived?.Invoke(this, new DownloadOutputEventArgs(jobId, output)); #if DEBUG System.Diagnostics.Debug.WriteLine(output); #endif }
private void OnProcessOutput(object sender, DataReceivedEventArgs e) { lock (_lock) { OutputReceived?.Invoke(this, e.Data); if (_hasExited && _localProcess.StandardOutput.EndOfStream) { Closed?.Invoke(this, _localProcess.ExitCode); } } }
/// <summary> /// to be called by view when ready /// </summary> /// <param name="shellProfile"></param> /// <param name="size"></param> /// <param name="sessionType"></param> public async Task StartShellProcess(ShellProfile shellProfile, TerminalSize size, SessionType sessionType) { _trayProcessCommunicationService.SubscribeForTerminalOutput(Id, t => OutputReceived?.Invoke(this, t)); var response = await _trayProcessCommunicationService.CreateTerminal(Id, size, shellProfile, sessionType).ConfigureAwait(true); if (response.Success) { FallbackTitle = response.ShellExecutableName; SetTitle(FallbackTitle); } }
private void OnOutputReceived(DataReceivedEventArgs srcArgs, bool isErr = false) { if (isErr) { outputBuilder.AppendError(srcArgs.Data); } else { outputBuilder.AppendOut(srcArgs.Data); } OutputReceived?.Invoke(this, new OutputReceivedEventArgs(srcArgs, isErr)); }
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { lock (_processLock) { if (_cancellationToken.IsCancellationRequested && !_process.HasExited) { _process.Kill(); return; } } OutputReceived?.Invoke(sender, e); }
/// <summary> /// 执行命令 /// </summary> /// <param name="fileName"></param> /// <param name="args"></param> /// <returns></returns> public ICommandResult Execute(string fileName, string args) { lock (_executingLock) { if (isDisposed) { throw new ObjectDisposedException(nameof(HestExecutor)); } //输出构造器 outputBuilder.Clear(); //记录开始时间 DateTime start = DateTime.Now; //开始进程 currentProcess = Process.Start(GetStartInfo(fileName, args)); //监听 currentProcess.OutputDataReceived += (s, e) => { outputBuilder.AppendOut(e.Data); OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, false)); }; currentProcess.ErrorDataReceived += (s, e) => { outputBuilder.AppendError(e.Data); OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, true)); }; currentProcess.BeginOutputReadLine(); currentProcess.BeginErrorReadLine(); //触发事件 CommandExecuting?.Invoke(this, new CommandExecutingEventArgs(fileName, args)); //等待进程结束 currentProcess.WaitForExit(); currentProcess.CancelErrorRead(); currentProcess.CancelOutputRead(); //记录结束时间 DateTime end = DateTime.Now; //构造结果对象 var result = new HestExecutorResult() { ExitCode = currentProcess.ExitCode, Output = outputBuilder.Result }; //触发结束事件 CommandExecuted?.Invoke(this, new CommandExecutedEventArgs(fileName, args, result, end - start)); //返回结果 return(result); }; }
/// <summary>Handler for all strings written to StdOut</summary> /// <param name="sendingProcess"></param> /// <param name="outLine"></param> private void OutputHandler(object sendingProcess, DataReceivedEventArgs outLine) { if (outLine.Data == null) finished = true; else if (!string.IsNullOrWhiteSpace(outLine.Data)) { OutputReceived?.Invoke(this, outLine); output.Append(outLine.Data + Environment.NewLine); if (WriteToConsole) Console.WriteLine(outLine.Data); } }
private void ReceiveOutput(IEnumerable <TerminalCode> codes) { lock (_bufferSync) { TerminalCode lastCode = new TerminalCode(TerminalCodeType.DummyCode); foreach (var code in codes) { ProcessTerminalCode(code, lastCode); lastCode = code; } } OutputReceived?.Invoke(this, EventArgs.Empty); }
private void OutputThread() { while (IsRunning) { _outputReceivedEvent.WaitOne(); while (IsRunning && _outputQueue.TryDequeue(out DataReceivedEventArgs data)) { OutputReceived?.Invoke(this, data); } _outputReceivedEvent.Reset(); } }
public void StartWithEvents() { Process.StartInfo.CreateNoWindow = true; Process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; Process.StartInfo.UseShellExecute = false; Process.StartInfo.RedirectStandardError = true; Process.StartInfo.RedirectStandardOutput = true; Process.EnableRaisingEvents = true; Process.ErrorDataReceived += (s, e) => OutputReceived?.Invoke(this, e.Data ?? ""); Process.OutputDataReceived += (s, e) => OutputReceived?.Invoke(this, e.Data ?? ""); Process.Exited += (s, e) => Exited?.Invoke(this, new EventArgs()); Process.Start(); Process.BeginErrorReadLine(); Process.BeginOutputReadLine(); }
public void SendOutput(string line) { if (string.IsNullOrEmpty(line)) { return; } Task.Run(() => { OutputReceived?.Invoke(this, line); lock (this) { _outputCache.AppendLine(line); if (_logWriter != null) { _logWriter.WriteLine(line); } } }); }
public MiFlashBatExecuteProcess(string batFileName, DeviceSerialNumber serial) { this.StartInfo = new ProcessStartInfo() { UseShellExecute = false, CreateNoWindow = true, Arguments = $"/q /c {batFileName} {serial.ToFullSerial()}", FileName = "cmd.exe", WorkingDirectory = AdbConstants.toolsPath, RedirectStandardError = true, RedirectStandardOutput = true, }; Logger.Warn(this, $"file path:{StartInfo.Arguments}"); OutputDataReceived += (s, e) => { OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, false)); }; ErrorDataReceived += (s, e) => { OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, true)); }; }
/// <summary> /// 触发OutputReceived事件 /// </summary> /// <param name="e"></param> private void OnOutputReceived(OutputReceivedEventArgs e) { if (e.Text == null || e.Text == "") { return; } var m = Regex.Match(e.Text, @"^___ec(?<code>-?\d+)$"); if (Regex.IsMatch(e.Text, @"^.+;\u0020echo\u0020___ec\$\?$")) { return; } if (m.Success) { builder.ExitCode = Convert.ToInt32(m.Result("${code}")); return; } if (_isEnableRead) { builder.AppendOut(e.Text); } OutputReceived?.Invoke(this, e); }
private void OnOutputDataReceived(object sender, DataReceivedEventArgs e) { if (e.Data == null) { return; } OutputReceived?.Invoke(this, new EventArgs <string>(e.Data)); if (e.Data.StartsWith(_serviceStartedMessage)) { var address = new Uri(e.Data.Substring(_serviceStartedMessage.Length)); ServiceUri = address; OnServiceStarted(); } if (e.Data.StartsWith(_serviceFailedMessage)) { var crashFilePath = e.Data.Substring(_serviceFailedMessage.Length); var crashDetails = File.ReadAllText(crashFilePath); var exception = JsonConvert.DeserializeObject <SerializableException>(crashDetails); OnServiceFailed(exception); } }
private void RaiseOutputReceivedEvent(string category, string data) { OutputReceived?.Invoke(this, new DebugeeOutputEventArgs(category, data)); }
void IDebugUnixShellCommandCallback.OnOutputLine(string line) { OutputReceived?.Invoke(this, line); }
public void Run() { _localProcess = new System.Diagnostics.Process(); _localProcess.StartInfo = processStartInfo; _localProcess.Exited += OnProcessExited; _localProcess.EnableRaisingEvents = true; _localProcess.Start(); _stdoutWriter = new StreamWriter(_localProcess.StandardInput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 4096, leaveOpen: false); _processReader = new StreamReader(_localProcess.StandardOutput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), false, BUFMAX, false); _outputReadTask = System.Threading.Tasks.Task.Run(() => ReadLoop(_processReader, _cancellationSource.Token, (line) => { OutputReceived?.Invoke(this, line); })); _localProcess.ErrorDataReceived += OnErrorOutput; _localProcess.Exited += OnProcessExited; _localProcess.BeginErrorReadLine(); }
public LocalRawCommandRunner(string command, string arguments) { _processStartInfo = new ProcessStartInfo(command, arguments); _processStartInfo.RedirectStandardError = true; _processStartInfo.RedirectStandardInput = true; _processStartInfo.RedirectStandardOutput = true; _processStartInfo.UseShellExecute = false; _processStartInfo.CreateNoWindow = true; _localProcess = System.Diagnostics.Process.Start(_processStartInfo); _localProcess.Exited += OnProcessExited; _localProcess.EnableRaisingEvents = true; _stdoutWriter = new StreamWriter(_localProcess.StandardInput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false), 4096, leaveOpen: false); _processReader = new StreamReader(_localProcess.StandardOutput.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: true), detectEncodingFromByteOrderMarks: false); _processError = new StreamReader(_localProcess.StandardError.BaseStream, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false, throwOnInvalidBytes: false), detectEncodingFromByteOrderMarks: false); System.Threading.Tasks.Task.Run(() => ReadLoop(_processReader, _cancellationSource.Token, (msg) => { OutputReceived?.Invoke(this, msg); })); System.Threading.Tasks.Task.Run(() => ReadLoop(_processError, _cancellationSource.Token, (msg) => { ErrorOccured?.Invoke(this, new ErrorOccuredEventArgs(new Exception(msg))); })); }
private void OnProcessOutput(object sender, DataReceivedEventArgs e) { OutputReceived?.Invoke(this, e.Data + '\n'); }
/// <summary> /// 触发输出事件 /// </summary> /// <param name="e"></param> /// <param name="isErr"></param> protected virtual void RaiseOutputReceived(DataReceivedEventArgs e, bool isErr) { callback?.Invoke(new OutputReceivedEventArgs(e, isErr)); OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, isErr)); }
private void OnOutputReceived(object sender, OutputReceivedEventArgs e) { OutputReceived?.Invoke(sender, e?.Output); }
protected virtual void OnOutputReceived(ProgramOutputReceivedEventArgs e) { OutputReceived?.Invoke(this, e); }
/// <summary> /// 触发输出事件 /// </summary> /// <param name="e"></param> /// <param name="isErr"></param> private void RaiseOutputReceived(DataReceivedEventArgs e, bool isErr) { callback?.Invoke(new OutputReceivedEventArgs(e, isErr)); OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, isErr)); }
protected void OnOutputReceived(OutputEventArgs e) { OutputReceived?.Invoke(this, e); }
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e) { outputBuilder !.AppendOut(e.Data); OutputReceived?.Invoke(this, new OutputReceivedEventArgs(e, false)); }
/// <summary> /// Invokes youtube-dl with the specified parameters and options. /// </summary> /// <param name="urls">The video URLs to be passed to youtube-dl.</param> /// <param name="options">An OptionSet specifying the options to be passed to youtube-dl.</param> /// <param name="ct">A CancellationToken used to cancel the download.</param> /// <param name="progress">A progress provider used to get download progress information.</param> /// <returns>The exit code of the youtube-dl process.</returns> public async Task <int> RunAsync(string[] urls, OptionSet options, CancellationToken ct, IProgress <DownloadProgress> progress = null) { var tcs = new TaskCompletionSource <int>(); var process = new Process(); var startInfo = new ProcessStartInfo() { CreateNoWindow = true, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true }; if (!String.IsNullOrEmpty(PythonPath)) { startInfo.FileName = PythonPath; startInfo.Arguments = $"\"{ExecutablePath}\" {ConvertToArgs(urls, options)}"; } else { startInfo.FileName = ExecutablePath; startInfo.Arguments = ConvertToArgs(urls, options); } process.EnableRaisingEvents = true; process.StartInfo = startInfo; var tcsOut = new TaskCompletionSource <bool>(); // this variable is used for tracking download states bool isDownloading = false; process.OutputDataReceived += (o, e) => { if (e.Data == null) { tcsOut.SetResult(true); return; } Match match; if ((match = rgxProgress.Match(e.Data)).Success) { if (match.Groups.Count > 1 && match.Groups[1].Length > 0) { float progValue = float.Parse(match.Groups[1].ToString(), CultureInfo.InvariantCulture) / 100.0f; Group totalGroup = match.Groups["total"]; string total = totalGroup.Success ? totalGroup.Value : null; Group speedGroup = match.Groups["speed"]; string speed = speedGroup.Success ? speedGroup.Value : null; Group etaGroup = match.Groups["eta"]; string eta = etaGroup.Success ? etaGroup.Value : null; progress?.Report( new DownloadProgress( DownloadState.Downloading, progress: progValue, totalDownloadSize: total, downloadSpeed: speed, eta: eta ) ); } else { progress?.Report(new DownloadProgress(DownloadState.Downloading)); } isDownloading = true; } else if ((match = rgxPlaylist.Match(e.Data)).Success) { var index = int.Parse(match.Groups[1].Value); progress?.Report(new DownloadProgress(DownloadState.PreProcessing, index: index)); isDownloading = false; } else if (isDownloading && (match = rgxPost.Match(e.Data)).Success) { progress?.Report(new DownloadProgress(DownloadState.PostProcessing, 1)); isDownloading = false; } Debug.WriteLine("[youtube-dl] " + e.Data); OutputReceived?.Invoke(this, e); }; var tcsError = new TaskCompletionSource <bool>(); process.ErrorDataReceived += (o, e) => { if (e.Data == null) { tcsError.SetResult(true); return; } Debug.WriteLine("[youtube-dl ERROR] " + e.Data); progress?.Report(new DownloadProgress(DownloadState.Error, data: e.Data)); ErrorReceived?.Invoke(this, e); }; process.Exited += async(sender, args) => { // Wait for output and error streams to finish await tcsOut.Task; await tcsError.Task; tcs.TrySetResult(process.ExitCode); process.Dispose(); }; ct.Register(() => { if (!tcs.Task.IsCompleted) { tcs.TrySetCanceled(); } try { if (!process.HasExited) { process.KillTree(); } } catch { } }); Debug.WriteLine("[youtube-dl] Arguments: " + process.StartInfo.Arguments); if (!await Task.Run(() => process.Start())) { tcs.TrySetException(new InvalidOperationException("Failed to start youtube-dl process.")); } process.BeginOutputReadLine(); process.BeginErrorReadLine(); progress?.Report(new DownloadProgress(DownloadState.PreProcessing)); return(await tcs.Task); }