Convert string containing quotes to command

I’m new to julia. I have the following strings readen from a json file:

pathtoexe = “c:\my soft\myexe.exe”
folder = “c:\folder with spaces”
mycommand= “‘pathtoexe’ /option /D=‘folder’”

The following commands replace pathtoexe and folder with their values in mycommand:

mycommand=replace(mycommand, “pathtoexe” => pathtoexe)
mycommand=replace(mycommand, “folder” => folder)

This gives “‘c:\my soft\myexe.exe’ /option /D=‘c:\folder with spaces’”, which is great.
Now i need to convert mycommand to a command before running it. Both commands:

cmd =$mycommand
cmd = @cmd(mycommand)

add extras “” that breaks it:

They gives "'c:\my soft\myexe.exe' /option /D='c:\folder with spaces'"
instead of 'c:\my soft\myexe.exe' /option /D='c:\folder with spaces'

then run fails.

How could i properly convert the string to a command ?

Try interpolating your pathtoexe etc directly into the command, with quoting as necessary.

Something like this:

  cmd = `'$pathtoexe' /option /D='$folder'`

You shouldn’t need to quote. Command strings aren’t a shell.


Exact, the problem is that i can’t write in the json file:

 "mycommand": `'$pathtoexe' /option /D='$folder'`,

because after

mycommand=get!(mydict, "mycommand",0)

fails. And if i write in json

"mycommand": "`'$pathtoexe' /option /D='$folder'`",


mycommand=get!(mydict, "mycommand",0) 

returns “'\$pathtoexe' /option /D='\$folder'”, thus escaping $ and not interpolating.

If you’re going to store a command in a JSON file, you should store it as list of strings, one per argument, not as a single string. This is how Julia stores a Cmd, actually.

You can call collect(cmd) (or cmd.exec) to get a list of strings from a cmd::Cmd, and you can call Cmd(list_of_strings) to reconstruct the Cmd.

(To store it as a single string, you’d have to do some parsing to break it up into arguments, and it’s easy to muck that up if there are spaces or other special characters.)

If you want to load a string/command from a file that has a $expression and then interpolate the value of the expression, then you basically have to invoke the Julia interpreter via eval, or write a custom interpreter.

1 Like

Thank you @stevengj for your answer, and sorry for this late reply.

I made the json line as you suggested:
mycommand= ["$pathtoexe","/option","/D=$folder"]

then the following instruction cancelled & changing it to \$, thus didn’t interpolate:
mycommand=Vector{String}(get!(soft, "mycommand",0))

But i could manage to get the desired result applying replace. to the list of string, before making the command:

mycommand = ["pathtoexe","/option","/D=folder"] (in json)
mycommand .=replace.(mycommand, "pathtoexe" => pathtoexe)
mycommand .=replace.(mycommand, "folder" => folder)
mycommand =Cmd(mycommand)

This is a satisfying solution for my needs, therefore I didn’t try your other idea with eval.
Thanks for your help.