Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

access Cmd elements as an array of strings #21197

Merged
merged 2 commits into from
May 19, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions base/process.jl
Original file line number Diff line number Diff line change
Expand Up @@ -805,3 +805,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