Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

julia

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

like image 404
xiaodai Avatar asked Aug 24 '26 19:08

xiaodai


2 Answers

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/

like image 161
hckr Avatar answered Aug 26 '26 22:08

hckr


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
like image 25
Oluwafemi Sule Avatar answered Aug 26 '26 23:08

Oluwafemi Sule