JohnJ
JohnJ

Reputation: 4823

Reading unbuffered keyboard input in Clojure

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.

Upvotes: 9

Views: 1265

Answers (2)

uvtc
uvtc

Reputation: 720

Maybe also have a look at clojure-lanterna.

Upvotes: 2

johnwayner
johnwayner

Reputation: 1165

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.

Upvotes: 6

Related Questions