Why does read-line not return after hitting ENTER (seems like a hang) using lein run, but works with lein repl?

ぃ、小莉子 提交于 2019-11-30 19:54:53

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.

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)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!