我希望将*in*
绑定到从字符串而不是“真实”输入流中读取的流。我该怎么做?
答案 0 :(得分:14)
结帐with-in-str
:
http://clojure.github.com/clojure/clojure.core-api.html#clojure.core/with-in-str
ClojureDocs有一个使用它的例子:
;; Given you have a function that will read from *in*
(defn prompt [question]
(println question)
(read-line))
user=> (prompt "How old are you?")
How old are you?
34 ; <== This is what you enter
"34" ; <== This is returned by the function
;; You can now simulate entering your age at the prompt by using with-in-str
user=> (with-in-str "34" (prompt "How old are you?"))
How old are you?
"34" ; <== The function now returns immediately
答案 1 :(得分:3)
这是我最终做的示例代码。这个想法是一个简单的服务器读/打开循环功能,它接收输入和输出流。我的问题是如何为这样的函数生成测试流,我认为字符串函数会这样做。相反,这就是我所需要的:
(ns test
(:use [clojure.java.io :only [reader writer]]))
(def prompt ">")
(defn test-client [in out]
(binding [*in* (reader in)
*out* (writer out)]
(print prompt) (flush)
(loop [input (read-line)]
(when input
(println (str "OUT:" input))
(print prompt) (flush)
(if (not= input "exit\n") (recur (read-line)) )
))))
(def client-stream (java.io.PipedWriter.))
(def r (java.io.BufferedReader. (java.io.PipedReader. client-stream)))
(doto (Thread. #(do (test-client r *out*))) .start)
(.write client-stream "test\n")