I want to define a function in racket that reads a racket code from an input file (for example "input.txt"), and runs the racket code and display the output. I tried doing this with the “read” function. But it only reads the first expression.
I want to define a function in racket that reads a racket code from an input file (for example "input.txt"), and runs the racket code and display the output. I tried doing this with the “read” function. But it only reads the first expression.
What you probably want is load. However it's mildly fiddly to get load to print the values of individual forms. Here is a simpler and probably not completely correct version of load which does this:
(define (load/print path
#:namespace (namespace (current-namespace))
#:printer (printer println)
#:suppress-void (suppress-void #t))
;; If the file starts with #lang &c this will let it be read, but the
;; printing won't generally be helpful in that case as it will be
;; read usually as a single (module ...) form.
(parameterize ([read-accept-reader #t]
[read-accept-lang #t])
(call-with-input-file
path
(λ (in)
(for ([form (in-port (λ (p) (read-syntax path p)) in)])
(call-with-values
(thunk (eval form namespace))
(λ vals
(for ([v (in-list vals)])
(unless (and suppress-void (void? v))
(printer v))))))
path))))
So given a file containing
1
(values 2 3 4)
"foo"
> (load/print "/path/to/my/file")
1
2
3
4
"foo"
"/tmp/file.rkt"