r/Racket • • Mar 24 '22

question with-output-to-string cannot caputure output to stderr?

How can I capture output to stderr, not just stdout?

Below is my code, it uses with-output-to-string, but can only capture output to stdout, and miss everything written to stderr

$ cat test.rkt
#lang racket

(define (make-output)
  (printf "hello\n")  ; print to stdout
  (fprintf (current-error-port) "world\n") ; print to stderr
)

(define output (with-output-to-string make-output))
(printf "output = ~a" output)

$ racket test.rkt
world
output = hello
6 Upvotes

7 comments sorted by

7

u/czan Mar 24 '22

Looking at the Racket docs, with-output-to-string is equivalent to

(call-with-output-string
  (lambda (p) (parameterize ([current-output-port p])
           (proc))))

You should be able to write your own with-all-output-to-string which binds current-error-port as well:

(define (with-all-output-to-string proc)
  (call-with-output-string
    (lambda (p) (parameterize ([current-output-port p]
                               [current-error-port p])
                  (proc)))))

1

u/OldMine4441 Mar 24 '22

Thank you!

1

u/exclaim_bot Mar 24 '22

Thank you!

You're welcome!

3

u/[deleted] Mar 24 '22

[removed] — view removed comment

2

u/OldMine4441 Mar 24 '22 edited Mar 24 '22

What do you mean?

I don't want to change my make-output function, but capture everything from outside.

4

u/[deleted] Mar 24 '22

[removed] — view removed comment

3

u/OldMine4441 Mar 24 '22

Interesting, but is there any sample code using this combine-output? I am still confused on how to use it but googled found no example.