'How to read a racket code from a file, and execute the code

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.



Solution 1:[1]

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"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ignis volens