I would like to retrieve the path of the currently running Julia interpreter from Julia. In Python, this can be achieved with sys.executable.
Base.julia_cmd() is probably what you need. It returns the full command line that was used to invoke the current julia process, with the default options spelled out. Base.julia_exename() returns the name of the executable.
julia> Base.julia_cmd()
/Users/aviks/dev/julia/julia5/usr/bin/julia -Cnative -J/usr/lib/julia/sys.dylib --compile=yes --depwarn=yes
julia> Base.julia_exename()
"julia"
If you just want the location of the julia executable, try one of these:
julia> julia_bin_exe = joinpath(Base.Sys.BINDIR,Base.julia_exename())
"/home/mkitti/src/julia/usr/bin/julia"
julia> Base.julia_cmd()
`/home/mkitti/src/julia/usr/bin/julia -Cnative -J/home/mkitti/src/julia/usr/lib/julia/sys.so -g1`
julia> typeof(Base.julia_cmd())
Cmd
julia> Base.julia_cmd()[1]
"/home/mkitti/src/julia/usr/bin/julia"
julia> julia_bin_exe == Base.julia_cmd()[1]
true
Related
I'm trying to run a shell command from Julia which needs to have an environment variable set to some specific value. I have two problems:
How to set environment variables to be used by Julia's
run(command, args...; wait::Bool = true) command?
How to pass special sign $ to this process without interpolating it? I want to test if the variable is available for my program.
What I have done so far:
Let's say I want to define an environment variable FOO=bar and check if it's accessible within the shell with shell command echo $FOO.
To prevent Julia interpolating $ I already quoted it like explained in the official documentation but then echo is printing $PATH and not its value.
So for FOO I got the following output
julia> run(`echo '$FOO'`)
$FOO
Process(`echo '$FOO'`, ProcessExited(0))
but would have expected something like
julia> run(`echo '$FOO'`)
Process(`echo '$FOO'`, ProcessExited(0))
if FOO is undefined or
julia> run(`echo '$FOO'`)
bar
Process(`echo '$FOO'`, ProcessExited(0))
if the value is set to bar.
Check out the Julia documentation on environment variables. You can set an environment variable with:
julia> ENV["FOO"] = "bar"
"bar"
and you can retrieve the value of an environment variable with:
julia> ENV["FOO"]
"bar"
julia> ENV["PATH"]
"really long string of my path"
As you've already stated, you can avoid interpreting the $ by single-quoting that part of your run command. I'm not totally sure what you are looking for there.
Not elegant, but this works:
julia> write("temp.sh", "echo foo=\$BAR");
julia> run(`bash temp.sh`)
foo=
Process(`bash temp.sh`, ProcessExited(0))
julia> ENV["BAR"] = "bar";
julia> run(`bash temp.sh`)
foo=bar
Process(`bash temp.sh`, ProcessExited(0))
I guess Julia injects the content of ENV into the shell before running the command. And that's all I needed to know as I'll be launching other executables which require some environment variables to be set. So when setting them inside ENV[], they will be available to the executables you run from within that Julia session.
In python to get the documentation of a function, we can type (for example) help(len).
How to do the same to get a function's documentation in Julia?
In Julia you can use a question mark followed by a function name, i.e. ?functionname, to get information about a function.
If you are using the REPL, the question mark will switch your julia> prompt to a help?> prompt - similar to how ] triggers the pkg> REPL mode. Check out the documentation for more information.
In Jupyter notebooks (IJulia) you just type ?println and there is no visible REPL mode change.
Example:
help?> println # I typed ?println
search: println printstyled print sprint isprint
println([io::IO], xs...)
Print (using print) xs followed by a newline. If io is not supplied, prints to stdout.
Examples
≡≡≡≡≡≡≡≡≡≡
julia> println("Hello, world")
Hello, world
julia> io = IOBuffer();
julia> println(io, "Hello, world")
julia> String(take!(io))
"Hello, world\n"
Note that this approach isn't restricted to functions. It works for all objects that have some docstrings attached to them:
help?> Sys.CPU_THREADS # docstring of a constant
Sys.CPU_THREADS
The number of logical CPU cores available in the system, i.e. the number of threads that the CPU can run concurrently. Note that this is not necessarily the number of CPU cores, for example, in the presence of hyper-threading (https://en.wikipedia.org/wiki/Hyper-threading).
See Hwloc.jl or CpuId.jl for extended information, including number of physical cores.
This is probably a newbie question... but is it possible to show the definition of a (user defined) function? While debugging/optimizing it is convenient to quickly see how a certain function was programmed.
Thanks in advance.
You can use the #edit macro, which is supposed to take you to the definition of a method, similarly to how the #which macro which shows the file and line # where that particular method was defined, for example:
julia> #which push!(CDFBuf(),"foo")
push!{T<:CDF.CDFBuf}(buff::T, x) at /d/base/DA/DA.jl:105
julia> #which search("foobar","foo")
search(s::AbstractString, t::AbstractString) at strings/search.jl:146
Note that methods that are part of Julia will show a path relative to the julia source directory "base".
While this is not an automatic feature available with Julia in general (as pointed out by Stefan), if you add docstrings when you define your initial function, you can always use the help?> prompt to query this docstring. For example
julia> """mytestfunction(a::Int, b)""" function mytestfunction(a::Int, b)
return true
This attaches the docstring "mytestfunction(a::Int, b)" to the function mytestfunction(a::Int, b). Once this is defined, you can then use the Julia help prompt (by typing ? at the REPL), to query this documentation.
help?> mytestfunction
mytestfunction(a::Int, b)
This is just a convenience but I think useful. Note that IPython allows a pure quit as does Matlab. Thus it would be reasonble in Julia to allow aliasing.
Thanks for any ideas as to how to do this.
Quitting in Julia
If you are using Julia from the command line then ctrl-d works. But if your intention is to quit by typing a command this is not possible exactly the way you want it because typing quit in the REPL already has a meaning which is return the value associated with quit, which is the function quit.
julia> quit
quit (generic function with 1 method)
julia> typeof(quit)
Function
Also Python
But that's not rare, for example Python has similar behavior.
>>> quit
Use quit() or Ctrl-D (i.e. EOF) to exit
Using a macro
Using \q might be nice in the Julia REPL like in postgres REPL, but unfortunately \ also already has a meaning. However, if you were seeking a simple way to do this, how about a macro
julia> macro q() quit() end
julia> #q
Causes Julia to Quit
If you place the macro definition in a .juliarc.jl file, it will be available every time you run the interpreter.
As waTeim notes, when you type quit into the REPL, it simply shows the function itself… and there's no way to change this behavior. You cannot execute a function without calling it, and there are a limited number of ways to call functions in Julia's syntax.
What you can do, however, is change how the Functions are displayed. This is extremely hacky and is not guaranteed to work, but if you want this behavior badly enough, here's what you can do: hack this behavior into the display method.
julia> function Base.writemime(io::IO, ::MIME"text/plain", f::Function)
f == quit && quit()
if isgeneric(f)
n = length(f.env)
m = n==1 ? "method" : "methods"
print(io, "$(f.env.name) (generic function with $n $m)")
else
show(io, f)
end
end
Warning: Method definition writemime(IO,MIME{symbol("text/plain")},Function) in module Base at replutil.jl:5 overwritten in module Main at none:2.
writemime (generic function with 34 methods)
julia> print # other functions still display normally
print (generic function with 22 methods)
julia> quit # but when quit is displayed, it actually quits!
$
Unfortunately there's no type more specific than ::Function, so you must completely overwrite the writemime(::IO,::MIME"text/plain",::Function) definition, copying its implementation.
Also note that this is pretty unexpected and somewhat dangerous. Some library may actually end up trying to display the function quit… causing you to lose your work from that session.
Related to Quitting in Julia
I was searching for something simple. This question hasn't been updated since 2017, as I try to learn Julia now, and spend some time googling for something simple and similar to python. Here, what I found:
You can use:
exit()
Note
I use julia 1.53
In R, starting from any working directory, I can do
setwd("~/Desktop")
and this is consistent with how my linux distribution interprets cd at the command line. But Julia does not seem to recognize the ~/ notation:
julia> cd("~/Desktop")
ERROR: chdir ~/Desktop: No such file or directory
in systemerror at error.jl:38
in cd at file.jl:13
Is this a bug?
The idiom is just different as you can see from the source. If you invoke cd() without arguments, it defaults to the home directory. The function homedir() can be used to prepend the home directory.
julia> homedir()
"/Users/jeffw"
julia> cd("/")
julia> pwd()
"/"
julia> cd()
julia> pwd()
"/Users/jeffw"
Combining things
julia> cd("$(homedir())/Desktop")
julia> pwd()
"/Users/jeffw/Desktop"
The problem is that Julia doesn't expand the ~. You need to manually provide the full path. This is being worked on, but I'm on my phone right now and can't find issue.