在Clojure中,可以通过重定向标准输出流来捕获远程REPL的输出并复制到PrintWriter中。下面是一个示例代码:
(require '[clojure.java.io :as io])
(require '[clojure.tools.nrepl :as repl])
(defn capture-output [code]
(let [writer (java.io.StringWriter.)
print-writer (java.io.PrintWriter. writer)]
(binding [*out* print-writer]
(eval code)
(.flush print-writer)
(.toString writer))))
(defn remote-eval [code]
(with-open [conn (repl/connect :port 7888)]
(let [response (-> (repl/client conn)
(repl/message {:op "eval"
:code code}))
output (get-in response [:value :out])]
output)))
(defn remote-eval-with-output [code]
(let [output (remote-eval code)]
(println output)
(capture-output (str "(println \"" output "\")"))))
在上面的代码中,remote-eval
函数用于远程执行代码并返回输出。remote-eval-with-output
函数在执行远程代码后,将输出打印到控制台并使用capture-output
函数将输出复制到PrintWriter
中。
请注意,上述代码中的端口号7888是示例值,你需要根据你实际的REPL配置进行相应的更改。
使用示例:
(remote-eval-with-output "(println \"Hello, World!\")")
这将在远程REPL上执行(println "Hello, World!")
,并将输出复制到PrintWriter
中,然后在控制台上打印输出。