2017-08-02 52 views
0

我想這樣做:如何在julia中使用不同變量的連接組合外部命令?

arg= " -l " 
cmd = "ls $arg " 
run(cmd) 

,但我找不到任何簡單的解決辦法做到這一點:

$ julia 
       _ 
    _  _ _(_)_  | A fresh approach to technical computing 
    (_)  | (_) (_) | Documentation: https://docs.julialang.org 
    _ _ _| |_ __ _ | Type "?help" for help. 
    | | | | | | |/ _` | | 
    | | |_| | | | (_| | | Version 0.6.0 (2017-06-19 13:05 UTC) 
_/ |\__'_|_|_|\__'_| | Official http://julialang.org/ release 
|__/     | x86_64-pc-linux-gnu 

julia> arg=" -l " 
" -l " 

julia> cmd=`ls $arg` 
`ls ' -l '` 

julia> run(cmd) 
ls: cannot access -l : No such file or directory 
ERROR: failed process: Process(`ls ' -l '`, ProcessExited(2)) [2] 
Stacktrace: 
[1] pipeline_error(::Base.Process) at ./process.jl:682 
[2] run(::Cmd) at ./process.jl:651 

julia> cmd="ls $arg" 
"ls -l " 

julia> run(`$cmd`) 
ERROR: could not spawn `'ls -l '`: no such file or directory (ENOENT) 
Stacktrace: 
[1] _jl_spawn(::String, ::Array{String,1}, ::Ptr{Void}, ::Base.Process, ::RawFD, ::RawFD, ::RawFD) at ./process.jl:360 
[2] #373 at ./process.jl:512 [inlined] 
[3] setup_stdio(::Base.##373#374{Cmd}, ::Tuple{RawFD,RawFD,RawFD}) at ./process.jl:499 
[4] #spawn#372(::Nullable{Base.ProcessChain}, ::Function, ::Cmd, ::Tuple{RawFD,RawFD,RawFD}) at ./process.jl:511 
[5] run(::Cmd) at ./process.jl:650 

我應該拆分得到的字符串到每個分出一部分(原因有沒有外殼做這個工作?)

順便說一句,如何獲取命令的退出狀態?

非常感謝

+1

嘗試'arg =「-l」'而不是'arg =「-l」'。這些空間混淆了'ls'。另外,請查看手冊中的[運行外部程序](https://docs.julialang.org/en/latest/manual/running-external-programs/)。 –

+0

我認爲這是同樣的問題。你的意思是這樣的:朱莉婭> ARG = 「 - 1」 「-l」 朱莉婭> CMD = 「LS $ ARG」 「ls -l命令」 朱莉婭 - >運行('$ cmd') 錯誤:無法不生成''ls -l'':沒有這樣的文件或目錄(ENOENT), –

+0

使用'cmd = \'ls $ arg \''(帶反引號) –

回答

1

嘗試:

arg = "-l" 
cmd = `ls $arg` 
run(cmd) 

而且讀running external programs 瞭解更多。

+0

好!對我的錯誤感到抱歉... 它也適用於更多變量:) 'arga =「-l」; argb =「-a」; cmd = \'ls $ arga $ argb \';運行(cmd)' –

+0

我搜索了關於運行外部程序的Julia文檔,但沒有發現關於退出狀態......任何想法? –

+1

在鏈接的文檔中,有一個段落,* run方法本身不返回任何內容,並且如果外部命令無法成功運行*,則會引發ErrorException。應該適用(雖然我現在還沒有嘗試過) –