Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure (read-line) doesn't wait for input

I am writing a text game in Clojure. I want the player to type lines at the console, and the game to respond on a line-by-line basis.

Research showed me that (read-line) is the way one is meant to get text lines from standard input in Clojure, but it is not working for me.

I am in a fresh Leiningen project, and I have added a :main clause to the project.clj pointing to the only source file:

(ns textgame.core)

(defn -main [& args]
  (println "Entering -main")
;  (flush)                      ;makes no difference if flush are commented out
  (let [input (read-line)]
    (println "ECHO:" input))
;  (flush)
  (println "Exiting -main"))

using lein run yields:

Entering -main
ECHO: nil
Exiting -main

In other words, there is no opportunity to enter text at the console for (read-line) to read.

How should I get Clojure to wait for characters and newline to be entered and return the corresponding string?

(I am using GNOME Terminal 2.32.1 on Linux Mint 11, Leiningen 1.6.1.1 on Java 1.6.0_26 Java HotSpot(TM) 64-Bit Server VM, Clojure version 1.2.1.)

Update: If I run lein repl, I can (println (read-line)), but not when I have a -main function and run using lein run.

like image 575
dukereg Avatar asked Oct 10 '11 00:10

dukereg


3 Answers

Try "lein trampoline run". See http://groups.google.com/group/leiningen/browse_thread/thread/a07a7f10edb77c9b for more details also from https://github.com/technomancy/leiningen:

Q: I don't have access to stdin inside my project.

A: There's a problem in the library that Leiningen uses to spawn new processes that blocks access to console input. This means that functions like read-line will not work as expected in most contexts, though the repl task necessarily includes a workaround. You can also use the trampoline task to launch your project's JVM after Leiningen's has exited rather than launching it as a subprocess.

like image 72
DanLebrero Avatar answered Nov 12 '22 22:11

DanLebrero


I have had similar problems and resorted to building a jar file and then running that.

lein uberjar
java -jar project-standalone.jar

It's a bit slower, though it got me unstuck. An answer that works from the repl would be better

like image 40
Arthur Ulfeldt Avatar answered Nov 13 '22 00:11

Arthur Ulfeldt


Wrap your read-line calls with the macro with-read-line-support which is now in ns swank.core [since swank-clojure 1.4+ I believe]:

(use 'swank.core)
(with-read-line-support 
  (println "a line from Emacs:" (read-line)))

Thanks to Tavis Judd for the fix.

like image 1
Don Avatar answered Nov 13 '22 00:11

Don