How do I request user input from a running script in Julia? In MATLAB, I would do:
result = input(prompt)
Thanks
The easiest thing to do is readline(stdin). Is that what you're looking for?
I like to define it like this:
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>
A function that checks that the answer provided matches the expected Type:
Function definition:
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
Function call (usage):
sentence = getUserInput(String,"Write a sentence:");
n = getUserInput(Int64,"Write a number:");
Now in Julia 1.6.1, it's as simple as typing:
num = readline()
Yea! without any arguments since the default value for the IO positional argument of the readline() function is "stdin". So in the above example Julia will read the input from the user and store it in the variable "num".
First I ran
Pkg.add("Dates")
then
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)
Related
I'm new to F#, apologies if I'm missing something obvious here.
I have the following code, with the intent to get user input and convert it to a uint:
let println ln =
printfn "%s" ln
let rec getUserKeyInput =
let x = System.Console.ReadKey()
string x
let getInputWithPrompt prompt =
println prompt
getUserKeyInput
let rec getUserUIntFromStr str =
try
let i = str |> uint
i
with
| :? System.FormatException -> println "Please enter a positive integer";
(getUserUIntFromStr (getUserKeyInput))
When getUserUIntFromStr is called with let i = getUserUIntFromStr str "Please enter a positive integer" is printed infinitely. I've also tried Console.ReadLine() and stdin.ReadLine(), both in interactive and from main, with the same results. It looks to me like none of the "Read" functions are waiting for input, but that doesn't seem right and I'm guessing I've done something wrong. Any suggestions?
getUserKeyInput is a value, not a function. It's evaluated only once at init time, not every time you reference it.
To make it a function, you need to give it a parameter. What type of parameter? Well, technically any type will do, but F# has you covered: for situations where you need to have some value, but there isn't a sensible value to use (which happens surprisingly often), there is a special type unit with a single value denoted as parentheses ():
let getUserKeyInput () =
let x = System.Console.ReadKey()
string x
(also note that rec is unnecessary, because the function isn't actually recursive)
(also note that ReadKey takes such parameter as well - it's the same deal there)
And then pass the parameter to call the function:
println "Please enter a positive integer"
getUserUIntFromStr (getUserKeyInput ())
In Julia v1.01 I would like to create a function from a string.
Background: In a numerical solver, a testcase is defined via a JSON file. It would be great if the user could specify the initial condition in string form.
This results in the following situation: Assume we have (from the JSON file)
fcn_as_string = "sin.(2*pi*x)"
Is there a way to convert this into a function fcn such that I can call
fcn(1.0) # = sin.(2*pi*1.0)
Performance is not really an issue, as the initial condition is evaluated once and then the actual computation consumes most of the time.
Can't get my code displayed correctly in a comment so here's a quick fix for crstnbr's solution
function fcnFromString(s)
f = eval(Meta.parse("x -> " * s))
return x -> Base.invokelatest(f, x)
end
function main()
s = "sin.(2*pi*x)"
f = fcnFromString(s)
f(1.)
end
julia> main()
-2.4492935982947064e-16
The functions Meta.parse and eval allow you to do this:
fcn_as_string = "sin.(2*pi*x)"
fcn = eval(Meta.parse("x -> " * fcn_as_string))
#show fcn(1.0)
This return -2.4492935982947064e-16 (due to rounding errors).
I am interested in a function to prompt the user for input with positional, keyword, and default arguments that is "Julian". I also want the documentation to be "Julian".
This example is what I have come up with so far:
"""
ask([prompt::String="prompt> "] [kw_prompt::String=""])::String
Prompt user for input and read and return a string from `stdin`.
If keyword argument, `kw_prompt`, is supplied, it will be the prompt.
If positional argument, `prompt`, is supplied, it will be the prompt.
If no parameter is supplied, the prompt will be "prompt> ".
# Examples
```julia_repl
julia> ask()
prompt> test
"test"
julia> ask("My prompt: ")
My prompt: test
"test"
julia> ask(kw_prompt="A long prompt >>> ")
A long prompt >>> test
"test"
```
"""
function ask(prompt::String="prompt> "; kw_prompt::String="")::String
if !isempty(kw_prompt)
print(kw_prompt)
elseif !isempty(prompt)
print(prompt)
end
return readline()
end # ask()
Any suggestions as to either the code or the documentation?
I would not call simultaneously supporting both positional and keyword args Julian. Just pick one.
If you really must, gloss over that detail in the documentation. Just chain the two together:
julia> """
ask([prompt="prompt>"])
"""
function ask(_prompt="prompt> "; prompt=_prompt)
print(prompt)
return readline()
end
ask (generic function with 2 methods)
julia> ask();
prompt>
julia> ask("foo> ");
foo>
julia> ask(prompt="bar> ");
bar>
Hi newbie here and I am trying to master recursive functions in Erlang. This function looks like it should work, but I cannot understand why it does not. I am trying to create a function that will take N and a string and will print out to stdout the string the number of times.
My code:
-module(print_out_n_times).
-export([print_it/2).
print_it(0, _) ->
"";
print_it(N, string) ->
io:fwrite(string),
print_it(N - 1, string).
The error I get is:
** exception error: no function clause matching print_it(5, "hello')
How can I make this work ?
Variables in Erlang start with a capital letter. string is an atom, not a variable named "string". When you define a function print_it(N, string), it can be called with any value for the first argument and only the atom string as the second. Your code should work if you replace string with String:
print_it(N, String) ->
io:fwrite(String),
print_it(N - 1, String).
I'am new to the Julia language and below is a code that I encode using the Jupyter Notebook, but there is no output but when i tried the same code using the REPL, there is an output. Please help me with this.
NOTE: the value of the variable is set to either 'S' or 's' and the input is a function that i copied from Ismael Venegas Castelló (Julia request user input from script). Thank you by the way Mr. Castelló.
if choose == 'S' || choose == 's'
str = input("Please input a String.");
che = input("please input a character to be search");
search(str, che);
end
Worked totally fine for me this way in JuliaPro(0.5.1.1).
julia> choose='s'
's'
julia> function input(prompt::AbstractString="")
print(prompt)
return chomp(readline())
end
input (generic function with 2 methods)
julia> if choose == 'S' || choose == 's'
str = input("Please input a String.");
che = input("please input a character to be search");
search(str, che);
end
Please input a String.It is working.
please input a character to be searchk
10:10