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

2019-02-13 23:53发布

问题:

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.

回答1:

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



回答2:

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.



回答3:

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.



回答4:

Not sure about the lein aspects of the problem, but definitely in emacs it is impossible to make stdin work. However, if you want to get text from the user, you can easily do it using a JOptionPane like this code from my little tic-tac-toe program:

(defn get-input []
  (let [input (JOptionPane/showInputDialog "Enter your next move (row/column)")]
    (map #(Integer/valueOf %) (.split input "/"))))