Skip to content

Commit

Permalink
Merge pull request #21197 from stevengj/cmdarray
Browse files Browse the repository at this point in the history
access Cmd elements as an array of strings
  • Loading branch information
StefanKarpinski authored May 19, 2017
2 parents 33fab6f + 5560ea3 commit 73b8dcb
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 0 deletions.
8 changes: 8 additions & 0 deletions base/process.jl
Original file line number Diff line number Diff line change
Expand Up @@ -824,3 +824,11 @@ wait(x::Process) = if !process_exited(x); stream_wait(x, x.exitnotify); end
wait(x::ProcessChain) = for p in x.processes; wait(p); end

show(io::IO, p::Process) = print(io, "Process(", p.cmd, ", ", process_status(p), ")")

# allow the elements of the Cmd to be accessed as an array or iterator
for f in (:length, :endof, :start, :eachindex, :eltype, :first, :last)
@eval $f(cmd::Cmd) = $f(cmd.exec)
end
for f in (:next, :done, :getindex)
@eval $f(cmd::Cmd, i) = $f(cmd.exec, i)
end
12 changes: 12 additions & 0 deletions doc/src/manual/running-external-programs.md
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,18 @@ julia> open(`less`, "w", STDOUT) do io
3
```

The program name and the individual arguments in a command can be accessed
and iterated over as if the command were an array of strings:
```jldoctest
julia> collect(`echo "foo bar"`)
2-element Array{String,1}:
"echo"
"foo bar"
julia> `echo "foo bar"`[2]
"foo bar"
```

## [Interpolation](@id command-interpolation)

Suppose you want to do something a bit more complicated and use the name of a file in the variable
Expand Down
11 changes: 11 additions & 0 deletions test/spawn.jl
Original file line number Diff line number Diff line change
Expand Up @@ -466,3 +466,14 @@ end
Base.showerror(io::IO, e::Error19864) = print(io, "correct19864")
throw(Error19864())'`),
stderr=catcmd)) == "ERROR: correct19864"

# accessing the command elements as an array or iterator:
let c = `ls -l "foo bar"`
@test collect(c) == ["ls", "-l", "foo bar"]
@test first(c) == "ls" == c[1]
@test last(c) == "foo bar" == c[3] == c[end]
@test c[1:2] == ["ls", "-l"]
@test eltype(c) == String
@test length(c) == 3
@test eachindex(c) == 1:3
end

0 comments on commit 73b8dcb

Please sign in to comment.