Running shell commands

To interact with the operating system from within the Julia REPL, there are a few helper functions available, as follows:

  • pwd(): this function prints the current directory, for example, "d:\test"
  • cd("d:\test\week1"): this function helps to navigate to subdirectories
  • ;in the interactive shell, you can also use shell mode using the ; modifier, for example: ; cd folder: navigates to folder

However, what if you want to run a shell command by using the operating system (the OS)? Julia offers efficient shell integration through the run function, which takes an object of type Cmd, defined by enclosing a command string in backticks (``).

The following are some examples for Linux or macOS X (at the time of writing: September 2018):

# Code in Chapter 9shell.jl: 
cmd = `echo Julia is smart` 
   typeof(cmd) #> Cmd  
   run(cmd) # returns Julia is smart
run(`date`) #> Sat Jul 14 09:44:50 GMT 2018 cmd = `cat file1.txt` run(cmd) # prints the contents of file1.txt

The preceding code does not work on Windows, although it worked until version 0.6. This is a bug in version 1.0 and is expected to be resolved in the near future.

Be careful to enclose the command text in backticks (`), not single quotes (').

If the execution of cmd by the OS goes wrong, run throws a failed process error. You might want to test the command first before running it; success(cmd) will return true if it executes successfully, otherwise it returns false.

Julia forks commands as child processes from the Julia process. Instead of immediately running the command in the shell, backticks create a Cmd object to represent the command. This can then be run, connected to other commands via pipes, and read or written to.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.150.231