[英]Why do string printed using 'print' in clojure only appear in my console after I use println?
I have the following code in clojure: 我在clojure中有以下代码:
(do
(println "starting....")
(sig! a 0)
(sig! b 0)
(future
(Thread/sleep 4000)
(println "switch 1")
(sig! a 1)
(sig! b 0)
(Thread/sleep 4000)
(println "switch 2")
(sig! a 0)
(sig! b 1)
(Thread/sleep 4000)
(println "switch 3")
(sig! a 1)
(sig! b 1)) nil))
I have some watchers that listen to the atoms a, b, s, and c1 and print out some strings when they change. 我有一些观察者听取原子a,b,s和c1并在它们改变时打印出一些字符串。 Using (print (str uid ":" @o "\\n")
or the println version. The clojure docs say print
and println
should behave exactly the same way, with the exception of the newline in println
, however I'm not seeing this. When the watcher uses println
I see the strings right away. When the watcher uses print
. I only see the output when the next println
is called. Below I have the output with println
vs with print
. With print
I only see the values up to the last println
. 使用(print (str uid ":" @o "\\n")
或println版本(print (str uid ":" @o "\\n")
文档说print
和println
行为应该完全相同,但println
中的换行除外,但是我没看到当观察者使用println
我立即看到了字符串。当观察者使用print
。我只看到下一个println
被调用时的输出。下面我有println
vs print
的输出。有print
我只看到值到最后一个println
。
starting....
switch 1
a:1
s:1
switch 2
a:0
b:1
s:0
s:1
switch 3
Now with println 现在有了println
starting....
switch 1
a:1
s:1
switch 2
a:0
b:1
s:0
s:1
switch 3
a:1
s:0
c1:1
As you can see the changes picked up by the watchers are printed in this case. 正如您所看到的,在这种情况下会打印观察者所选择的更改。 I'm using clojure 1.5. 我正在使用clojure 1.5。 It almost seems like a print
requires a println
to flush its contents to console. 它几乎看起来像print
需要println
将其内容刷新到控制台。
After looking more closely at the Clojure source code for println
and print
. 仔细查看了println
和print
的Clojure源代码 。 The difference is that println
calls prn
and print calls pr
. 不同之处在于println
调用prn
和print calls pr
。 In the prn
the function newline
is called. 在prn
, 调用函数 newline
。 It then checks for flush-on-new-line and if it is true it explicitly calls flush
. 然后它检查flush-on-new-line ,如果为true则显式调用flush
。 Therefore calling print
with any number of newlines ("\\n") in the string will not flush to the output stream, you must either call newline
, or call flush
directly. 因此,在字符串中使用任意数量的换行符(“\\ n”)调用print
将不会刷新到输出流,您必须调用newline
或直接调用flush
。
Output doesn't actually go to console until it is flushed. 在刷新之前,输出实际上不会进入控制台。 Generally, printing a newline character is the default signal for the console to flush the output. 通常,打印换行符是控制台刷新输出的默认信号。 You can generally force this in most languages with a call to a flush function, in most IO libraries. 在大多数IO库中,通常可以通过调用flush函数在大多数语言中强制执行此操作。
According to the Clojure documentation , output is flushed by default on every newline. 根据Clojure文档 ,默认情况下会在每个换行符上刷新输出。 So you'll probably have to explicitly flush the output to get what you want. 因此,您可能必须显式刷新输出才能获得所需内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.