【发布时间】:2011-06-18 19:22:49
【问题描述】:
我想将*in* 绑定到从字符串而不是“真实”输入流中读取的流。我该怎么做?
【问题讨论】:
标签: clojure inputstream
我想将*in* 绑定到从字符串而不是“真实”输入流中读取的流。我该怎么做?
【问题讨论】:
标签: clojure inputstream
查看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
【讨论】:
这是我最终所做的示例代码。这个想法是一个简单的服务器读取/打印循环函数,它接受输入和输出流。我的问题是如何为这样的函数生成测试流,我认为字符串函数可以。相反,这正是我所需要的:
(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")
【讨论】: