在Julia中,向REPL显示文本文件
给定当前目录中的文本文件“hello.jl”:在Julia中,向REPL显示文本文件,julia,Julia,给定当前目录中的文本文件“hello.jl”: " Example hello world program." function hello() println("hello, world") end 您将如何向Julia 1.0.0 REPL显示此内容 这就是我到目前为止所做的: julia> disp(f) = for line in readlines(open(f)); println(line); end disp (generic function with 1 me
" Example hello world program."
function hello()
println("hello, world")
end
您将如何向Julia 1.0.0 REPL显示此内容
这就是我到目前为止所做的:
julia> disp(f) = for line in readlines(open(f)); println(line); end
disp (generic function with 1 method)
julia> disp("hello.jl")
" Example hello world program."
function hello()
println("hello, world")
end
Julia中是否有内置命令来执行此操作?在Linux中,您可以使用
run
函数并向其传递Cmd
参数来运行cat
系统命令
键入分号编码>以切换到外壳模式:
shell> cat hello.jl
"Example hello world program."
function hello()
println("hello, world")
end
使用run
函数在Julia之外执行命令:
julia> run(`cat hello.jl`) # Only works on Unix like systems.
"Example hello world program."
function hello()
println("hello, world")
end
Process(`cat hello.jl`, ProcessExited(0))
在Windows中,type
命令应类似于Unixcat
:
julia> show_file(path::AbstractString) = run(@static Sys.isunix() ? `cat $path` : `type $path`)
show_file (generic function with 1 method)
run
返回进程
对象:
julia> show_file("hello.jl")
"Example hello world program."
function hello()
println("hello, world")
end
Process(`cat hello.jl`, ProcessExited(0))
使用分号代码>在行尾,要抑制REPL中的返回输出,请执行以下操作:
julia> show_file("hello.jl");
"Example hello world program."
function hello()
println("hello, world")
end
或者,如果愿意,您可以在show_file
的末尾返回nothing
。在julia REPL中,点击
;
要进入REPL的内置shell模式,则
shell> head path/to/my/filename
println(字符串(读(“hello.jl”))
或
“hello.jl”|>read |>String |>println
我会改为在shell模式下执行cat hello.jl
。或者也可以使用disp(file)=(println.(readlines(file));nothing)
,使用广播语法,注意readlines
如何处理打开和读取文件,而无需使用open
@gnimu是,我刚试过,效果很好。谢谢。read
还有一个方法read(filename::AbstractString,::Type{T}),其中T
一步完成字符串转换:read(“hello.jl”,string)
println(string(read)(“hello.jl”))
工作正常<代码>“hello.jl”|>read |>String |>println
也可以使用read(“hello.jl”,String)
工作,但在字符串中保留转义字符。您也可以在流中执行(不要一次将所有内容读入内存):write(stdout,open(“hello.jl”)
我想在这种情况下,OP需要,cat
,不是head
。我在Linux中是如何操作的——对于长度未知的文件,使用head或head-n可能更安全。如果文件大小令人担忧,那么less
也是一个不错的选择。