9

How does one read a single keystroke from the terminal (not Swing) in Clojure?

I have tried a few things including various versions of the JLine library, but have not gotten it working (see example below).

I will happily accept a working, Unix-only (Mac, Linux, ...) example. Ideally I'd like to know how to switch buffering off for both stdin and stdout.

Here's something close:

;; project.clj dependencies:
;; [[org.clojure/clojure "1.4.0"]
;;  [jline/jline "2.8"]])

(ns slosh.core
  (:import [jline.console ConsoleReader])
  (:gen-class))    

(defn -main []
  (println "start")
  (let [cr (ConsoleReader.)]
    (.readCharacter cr)
    (println "done")))

This prints "start" but does not respond to any input except control-C.

JohnJ
  • 4,753
  • 2
  • 28
  • 40

2 Answers2

6

I'm not sure how you are running this, but if you are using lein run, you will run into problems. Try using lein trampoline run.

I would link Single character console input in java/clojure but I don't seem to have enough Internet Points to do that.

Community
  • 1
  • 1
johnwayner
  • 1,155
  • 11
  • 8
  • `lein trampoline run` does indeed work, as does running from the überjar. Any ideas why one works and not the other? – JohnJ Nov 18 '12 at 12:10
  • 1
    The `sh` function used with `lein run` only hooks up `out` and `err` of the project run as a subprocess (see https://github.com/technomancy/leiningen/blob/master/leiningen-core/src/leiningen/core/eval.clj#L155). `trampoline` causes the project to be run as an independent process with its `in`, `out`, and `err` hooked up by the shell. – johnwayner Nov 18 '12 at 23:02
2

Maybe also have a look at clojure-lanterna.

uvtc
  • 710
  • 3
  • 8
  • Also looks good - thanks for the link. Will try that library if I get blocked using jline2. – JohnJ Nov 19 '12 at 03:54