Why does read-line not return after hitting ENTER

2019-02-13 11:30发布

问题:

The problem at hand is that when I run my program with lein run it gets to the (read-line) part and I can't get out of it, meaning: read-line never returns.

Here is the relevant code:

(def command (atom ""))

(defn print-prompt []
  (print "prompt> ")
  (flush)
)

(defn ask-for-input []
    (print-prompt)
    (let [x (str (read-line))]
      (println (str "User input: " x))
      (reset! command x)
    )
)

I never see the "User input: " string on screen. The strange part is, if I run lein repl and call (ask-for-input) then it works correctly :S

回答1:

Try lein trampoline run, it works.

The following is from leiningen FAQ:

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

A: This is a limitation of the JVM's process-handling methods; none of them expose stdin correctly. 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.



回答2:

I tried your source code, but omitted the flush. It worked without a problem. What version of Clojure are you using? I tried the following code with Clojure 1.3.

(def command (atom 0))

(defn print-prompt []
  (print "prompt> ")
)

(defn ask-for-input 
    []
    (print-prompt)
    (let [x (str (read-line))]
      (println (str "User input: " x))
      (reset! command x)
    ))

Edit: I altered one of your functions that I copied and tested with, and it works now with standalone and lein run. You had (flush) in your original example.

(defn print-prompt []
  (print "prompt> ")
  (flush)
)

From what I can garner, println causes a flush, print doesn't, and you need a flush after print.

I am adding this information in case it might be of help. I have a Clojure project called repl-test. Here is my repl-test project's core.clj file header. Your source, already posted, is in this file with some other functions, not related to your post.

(ns repl-test.core
  (:gen-class)
  (:use clojure.contrib.command-line)
  (:require [clojure.contrib.string :as cstr])
  (:require [clojure.contrib.trace :as ctr])
  (:require [clojure.string :as sstr])
  (:use clojure-csv.core))

And here is the project.clj file:

(defproject repl-test "0.0.1-SNAPSHOT"
  :description "TODO: add summary of your project"
  :dependencies [[org.clojure/clojure "1.3.0"]
                 [org.clojure/clojure-contrib "1.2.0"]
                 [clojure-csv/clojure-csv "1.2.4"]
                 [org.clojure/tools.cli "0.1.0"]
                 [clj-http "0.1.3"]]
   :aot [repl-test.core]
   :main repl-test.core)