Last active
          September 25, 2023 06:05 
        
      - 
      
 - 
        
Save watzon/87da7212609314cdb45626a0296b4511 to your computer and use it in GitHub Desktop.  
    Crystal function to capture stdin and stdout and redirect them within the block, returning an array containing 2 strings
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | def with_std(&block) | |
| original_stdout = File.open("/dev/null") | |
| original_stdout.reopen(STDOUT) | |
| original_stderr = File.open("/dev/null") | |
| original_stderr.reopen(STDERR) | |
| stdout_reader, stdout_writer = IO.pipe | |
| stderr_reader, stderr_writer = IO.pipe | |
| STDERR.reopen(stderr_writer) | |
| STDOUT.reopen(stdout_writer) | |
| yield | |
| stdout_writer.close | |
| stderr_writer.close | |
| STDOUT.reopen(original_stdout) | |
| STDERR.reopen(original_stderr) | |
| return [stdout_reader.gets_to_end, stderr_reader.gets_to_end] | |
| ensure | |
| [stdout_reader, stderr_reader].each(&.try(&.close)) | |
| STDOUT.reopen(original_stdout.not_nil!) | |
| STDERR.reopen(original_stderr.not_nil!) | |
| end | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment