8

I am trying to use run() or success() to execute a Python script from Julia.

I can run it fine if I specify the command by hand:

julia> run(`python sample.py`)
woo! sample

However, if I try to run it via a string argument, it suddenly does not work.

julia> str = "python sample.py"
"python sample.py"

julia> run( `$str` )
ERROR: could not spawn `'python sample.py'`: no such file or directory (ENOENT)
 in _jl_spawn at process.jl:217
 in spawn at process.jl:348
 in spawn at process.jl:389
 in run at process.jl:478

Specifying the full path for sample.py produces the same result. Oddly enough, just running python as a string does work:

julia> str = "python"
"python"

julia> run( `$str` )
Python 2.7.3 (default, Feb 27 2014, 19:58:35) 
[GCC 4.6.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> 

Am I doing something incorrectly?

Thank you

1 Answer 1

8

This is due to the specialized command interpolation. It treats each interpolated part as an independent section of the command. While slightly unintuitive at times, it allows you to completely forget about all the difficulties of quoting, whitespace, etc.

When you run(`$str`), it's treating str as the entire command name, which is why it complains that it cannot find the executable with the name "python sample.py". If you'd like to run "python" with the argument "sample.py", you need two interpolations:

cmd = "python"
arg = "sample.py"
run(`$cmd $arg`)

This allows your argument to have a space and it will still be treated all as the first argument.

If you really want to use a string like "python sample.py", you can split it at its whitespace:

str = "python sample.py"
run(`$(split(str))`) # strongly unadvised

But note that this will be very fragile to the argument name. If you ever want to run a file named "My Documents/sample.py" this will break, whereas the first interpolation will just work.

Sign up to request clarification or add additional context in comments.

3 Comments

Probably unsurprisingly, there's an exactly parallel issue when using Python (hence subprocess.call(["python", "sample.py"])).
I can't see an easy way to build up commands with optional arguments as julia quotes them eg. optionalArg="" ; ls $optionalArg . :'( Only way is to manually building up an array of arguments where you have to quote each one :'(
If you interpolate a single array into the command it passes each element as a separate argument: args = ["-l","-a"]; run(`ls $args .`)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.