Julia 传递参数,读取命令行 [英] Julia passing arguments, reading the command line

查看:33
本文介绍了Julia 传递参数,读取命令行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

I am trying to prompt the user of my .jl file to enter user entered multiple destinations.

Basically I need the user to give an input & an output. I know in java you would use a scanner, or accept arguments when it is compiled in the command line. I am fine with either option. From what I have found looking through the Julia Documentation I think I could accomplish the first way of assigning a variable to the readline function.

(String)in = (String)Readline(STDIN)

From my understanding the variable 'in' should now contain a String of the user's input. I am encountering an error, in that when I compile my .jl code, because my command prompt does not stop to read user input, and just finishes reading the .jl code.

解决方案

The first item to note in the code in your question is:

(String)in = (String)Readline(STDIN)

Julia 1.0.0 now uses stdin instead of STDIN.

Next, the (String) typecasting is not something you need or want to do in Julia.

Thus your code could read (though we get an error):

julia> in = readline(stdin)
This is a test.
ERROR: cannot assign variable Base.in from module Main

So variable in is in conflict with a Julia Base.in variable. Just use a another variable name.

julia> response = readline(stdin)
This is a test.
"This is a test"

This code is now working, but it has no prompt. Your answer provides an example input function with a prompt which you defined like this:

julia> function input(prompt::AbstractString="")
           print(prompt)
           return chomp(readline())
       end
input (generic function with 2 methods) 

The chomp function removes a single trailing newline character from the input string. Docs here.

Example use of the function here:

julia> input_file = input("Please enter input file name: ")
Please enter input file name: Data.txt
"Data.txt"

julia> output_file = input("Please enter output file name: ")
Please enter output file name: Output.txt
"Output.txt"

Command Line Args Method

As the docs point out, to just print out the arguments given to a script, you can do something like this:

println("Arguments passed to ", PROGRAM_FILE, ":")
for arg in ARGS
    println(arg)
end

Here is an example of above code running on the Windows command line:

c:OS_Prompt>julia PrintArgs.jl Data.txt Output1.txt Output2.txt Output3.txt
Arguments passed to PrintArgs.jl:
Data.txt
Output1.txt
Output2.txt
Output3.txt

You can also print out the script file name as shown, PrintArgs.jl.

这篇关于Julia 传递参数,读取命令行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆