Julia脚本请求用户输入

33

我该如何在Julia中从正在运行的脚本请求用户输入?在MATLAB中,我会这样做:

result = input(prompt)

谢谢

5个回答

34

最简单的方法是readline(stdin)。这是否是您要寻找的内容?


5
目前这样做就可以解决问题,但我们希望有一个更像 readline 库的系统那样复杂的东西。Keno 纯 Julia 重新实现 REPL 将提供很好的框架来完成类似于此类交互式操作。 - StefanKarpinski
2
在 Julia 0.7 及更高版本(可能包括 0.6)中,现在使用的是 stdin - niczky12

19

我喜欢这样定义:

julia> @doc """
           input(prompt::AbstractString="")::String

       Read a string from STDIN. The trailing newline is stripped.

       The prompt string, if given, is printed to standard output without a
       trailing newline before reading input.
       """ ->
       function input(prompt::AbstractString="")::String
           print(prompt)
           return chomp(readline())
       end
input (generic function with 2 methods)

julia> x = parse(Int, input());
42

julia> typeof(ans)
Int64

julia> name = input("What is your name? ");
What is your name? Ismael

julia> typeof(name)
String

help?> input
search: input

  input(prompt::AbstractString="")::String

  Read a string from STDIN. The trailing newline is stripped.

  The prompt string, if given, is printed to standard output without a trailing newline before reading input.

julia>

1
很好的答案,这对我帮助很大。 - user5458362

2

一个检查所提供答案是否与预期类型匹配的函数:

函数定义:

function getUserInput(T=String,msg="")
  print("$msg ")
  if T == String
      return readline()
  else
    try
      return parse(T,readline())
    catch
     println("Sorry, I could not interpret your answer. Please try again")
     getUserInput(T,msg)
    end
  end
end

函数调用(使用方法):

sentence = getUserInput(String,"Write a sentence:");
n        = getUserInput(Int64,"Write a number:");

2
现在在Julia 1.6.1中,只需键入以下内容即可:

num = readline()

没错!由于readline()函数的IO位置参数的默认值是"stdin",所以在上面的例子中,Julia将从用户那里读取输入并将其存储在变量"num"中。


1
这应该是现在被接受的答案,请点赞。这似乎是Julia的一个常见问题,许多stackoverflow上高票/被接受的答案已经过时了。顺便说一下,注意这个功能在VS Code上已经有4年没能正常工作了,而我相信这是Julia的“标准”编辑器。请参考https://github.com/julia-vscode/julia-vscode/issues/785 - GeoffDS

-4

首先我运行了 Pkg.add("Dates") 然后

using Dates

println()
print("enter year  "); year = int(readline(STDIN))
print("enter month "); month = int(readline(STDIN))
print("enter day   "); day = int(readline(STDIN))

date = Date(year, month, day)
println(date)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接