Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading unbuffered keyboard input in Clojure

Tags:

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.

like image 344
JohnJ Avatar asked Nov 17 '12 22:11

JohnJ


2 Answers

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.

like image 52
johnwayner Avatar answered Nov 08 '22 08:11

johnwayner


Maybe also have a look at clojure-lanterna.

like image 2
uvtc Avatar answered Nov 08 '22 07:11

uvtc