Capturing a print statement in f #

I was wondering if there is a good way to define a function captureOutputthat takes a function fthat can contain print instructions and return everything that was printed f. eg.

let f x = print "%s" x
let op = captureOutput (f "Hello World")

val op : string = "Hello World"

I thought there might be a good way to do this asynchronously with Console.ReadLine(), but I could not process anything.

Greetings

EDIT:

Based on the comments of Fedor Soikin, the following code does what I want:

let captureOutput f x =
    let newOut = new IO.StringWriter()
    Console.SetOut(newOut)
    f x
    Console.SetOut(Console.Out)
    newOut.ToString()
+4
source share
2 answers

You can temporarily replace standard recording output with Console.SetOut.

: , . , , "".

, , . . - , , :

type Printer = abstract member print (fmt: StringFormat<'T, unit>) : 'T

let captureOutput f =
   let mutable output = ""
   let print s = output <- output + s
   f { new Printer with member _.print fmt = kprintf print fmt }
   output

let f x (p: Printer) = p.print "%s" x 
let op = captureOutput (f "Hello World") 

( , print )

+5

@FyodorSoikin ( , ):

let captureOutput f =
    use writer = new StringWriter()
    use restoreOut =
        let origOut = Console.Out
        { new IDisposable with member __.Dispose() = Console.SetOut origOut }
    Console.SetOut writer
    f ()
    writer.ToString ()

let f x () = printf "%s" x
let op = captureOutput (f "Hello World")

(N.b. f, – captureOutput , ).

IDisposable , f .

+3

Source: https://habr.com/ru/post/1672407/


All Articles