xiaodai
xiaodai

Reputation: 16004

Julia: How to execute a system command from Julia code?

I have created a string

x = "ls"

and I wanted to execute x as a string from Julia. How do I do that?

ls is just a contrivded example I actually wanted to execute a more complicated command, so please don't tell me pwd() works.

The actual command might be split c:/data/Performance_All/Performance_2000Q1.txt -n l/3 -d /c/data/Performance_All_split/Performance_2000Q1.txt

Upvotes: 3

Views: 8802

Answers (3)

In Julia+Jupyter you can just use a semicolon ;, e.g.

; ls

Upvotes: 0

hckr
hckr

Reputation: 5583

You can simply use run with a Cmd object. You can use strings to create Cmd objects via `` and interpolation operator $ or through Cmd constructor.

Here's an example. You might want to check the file paths though.

x = "split"
path1 = "c:/data/Performance_All/Performance_2000Q1.txt"
option1 = "-n l/3"
option2 = "-d"
path2 = "/c/data/Performance_All_split/Performance_2000Q1.txt"
run(`$x $path1 $option1 $option2 $path2`) # remember the backticks ``

You do not need to use quotes even when there is a whitespace in the file paths. The command object runs the program and passes the parameters directly to it, not through shell.

You might want to read the relevant manual entry. https://docs.julialang.org/en/v1/manual/running-external-programs/

Upvotes: 9

Oluwafemi Sule
Oluwafemi Sule

Reputation: 38922

Base::read can be used for running a command and reading its results.

You can find usage examples for running command in the test/spawn.jl

Important is wrapping the command and its arguments in backticks. e.g.

out = ""
try
    global out
    out = read(`$x`, String)
catch ex
    @error ex
end

Upvotes: 3

Related Questions