Command-line Interface
Using arguments inside scripts
Al ejecutar un script usando julia
, puedes pasar argumentos adicionales a tu script:
$ julia script.jl arg1 arg2...
Estos argumentos adicionales de la línea de comandos se pasan en la constante global ARGS
. El nombre del script en sí se pasa como el global PROGRAM_FILE
. Tenga en cuenta que ARGS
también se establece cuando se proporciona una expresión de Julia utilizando la opción -e
en la línea de comandos (vea la salida de ayuda de julia
a continuación), pero PROGRAM_FILE
estará vacío. Por ejemplo, para simplemente imprimir los argumentos dados a un script, podría hacer esto:
$ julia -e 'println(PROGRAM_FILE); for x in ARGS; println(x); end' foo bar
foo
bar
O podrías poner ese código en un script y ejecutarlo:
$ echo 'println(PROGRAM_FILE); for x in ARGS; println(x); end' > script.jl
$ julia script.jl foo bar
script.jl
foo
bar
El delimitador --
se puede usar para separar los argumentos de línea de comandos destinados al archivo de script de los argumentos destinados a Julia:
$ julia --color=yes -O -- script.jl arg1 arg2..
Consulta también Scripting para más información sobre cómo escribir scripts en Julia.
The Main.main
entry point
A partir de Julia 1.11, Base
exporta el macro @main
. Este macro se expande al símbolo main
, pero al concluir la ejecución de un script o expresión, julia
intentará ejecutar la función Main.main(ARGS)
si tal función ha sido definida y este comportamiento fue optado al usar el macro @main
.
Esta función está destinada a ayudar en la unificación de flujos de trabajo compilados e interactivos. En los flujos de trabajo compilados, cargar el código que define la función main
puede estar separada espacial y temporalmente de la invocación. Sin embargo, para los flujos de trabajo interactivos, el comportamiento es equivalente a llamar explícitamente a exit(main(ARGS))
al final del script o expresión evaluada.
El punto de entrada especial Main.main
se agregó en Julia 1.11. Para compatibilidad con versiones anteriores de Julia, agrega un @isdefined(var"@main") ? (@main) : exit(main(ARGS))
explícito al final de tus scripts.
Para ver esta función en acción, considera la siguiente definición, que ejecutará la función print a pesar de no haber una llamada explícita a main
:
$ julia -e '(@main)(args) = println("Hello World!")'
Hello World!
$
Solo el enlace main
en el módulo Main
tiene este comportamiento y solo si se utilizó el macro @main
dentro del módulo definitorio.
Por ejemplo, usar hello
en lugar de main
no resultará en la ejecución de la función hello
:
$ julia -e 'hello(ARGS) = println("Hello World!")'
$
y tampoco lo hará una definición simple de main
:
$ julia -e 'main(ARGS) = println("Hello World!")'
$
Sin embargo, la opción de participar no necesita ocurrir en el momento de la definición:
$ julia -e 'main(ARGS) = println("Hello World!"); @main'
Hello World!
$
El enlace main
puede ser importado de un paquete. Un paquete de hola mundo definido como
module Hello
export main
(@main)(args) = println("Hello from the package!")
end
puede ser utilizado como:
$ julia -e 'using Hello'
Hello from the package!
$ julia -e 'import Hello' # N.B.: Execution depends on the binding not whether the package is loaded
$
Sin embargo, ten en cuenta que la recomendación actual de mejores prácticas es no mezclar el código de la aplicación y el código de la biblioteca reutilizable en el mismo paquete. Las aplicaciones auxiliares pueden distribuirse como paquetes separados o como scripts con puntos de entrada main
separados en la carpeta bin
de un paquete.
Parallel mode
Julia se puede iniciar en modo paralelo con las opciones -p
o --machine-file
. -p n
lanzará n
procesos de trabajo adicionales, mientras que --machine-file file
lanzará un trabajador por cada línea en el archivo file
. Las máquinas definidas en file
deben ser accesibles a través de un inicio de sesión ssh
sin contraseña, con Julia instalada en la misma ubicación que el host actual. Cada definición de máquina tiene la forma [count*][user@]host[:port] [bind_addr[:port]]
. user
se establece de forma predeterminada en el usuario actual, port
en el puerto estándar de ssh. count
es el número de trabajadores que se generarán en el nodo y se establece de forma predeterminada en 1. La opción bind-to bind_addr[:port]
especifica la dirección IP y el puerto que otros trabajadores deben usar para conectarse a este trabajador.
Startup file
Si tienes código que deseas ejecutar cada vez que se ejecute Julia, puedes colocarlo en ~/.julia/config/startup.jl
:
$ echo 'println("Greetings! 你好! 안녕하세요?")' > ~/.julia/config/startup.jl
$ julia
Greetings! 你好! 안녕하세요?
...
Tenga en cuenta que, aunque debería tener un directorio ~/.julia
una vez que haya ejecutado Julia por primera vez, es posible que deba crear la carpeta ~/.julia/config
y el archivo ~/.julia/config/startup.jl
si lo utiliza.
Para que el código de inicio se ejecute solo en The Julia REPL (y no cuando julia
se ejecuta por ejemplo en un script), usa atreplinit
en startup.jl
:
atreplinit() do repl
# ...
end
Command-line switches for Julia
Hay varias formas de ejecutar código Julia y proporcionar opciones, similares a las disponibles para los programas perl
y ruby
:
julia [switches] -- [programfile] [args...]
La siguiente es una lista completa de los interruptores de línea de comandos disponibles al iniciar julia (un '*' marca el valor predeterminado, si corresponde; los ajustes marcados '($)' pueden activar la precompilación de paquetes):
Switch | Description |
---|---|
-v , --version | Display version information |
-h , --help | Print command-line options (this message) |
--help-hidden | Print uncommon options not shown by -h |
--project[={<dir>|@.}] | Set <dir> as the active project/environment. The default @. option will search through parent directories until a Project.toml or JuliaProject.toml file is found. |
-J , --sysimage <file> | Start up with the given system image file |
-H , --home <dir> | Set location of julia executable |
--startup-file={yes*|no} | Load JULIA_DEPOT_PATH/config/startup.jl ; if JULIA_DEPOT_PATH environment variable is unset, load ~/.julia/config/startup.jl |
--handle-signals={yes*|no} | Enable or disable Julia's default signal handlers |
--sysimage-native-code={yes*|no} | Use native code from system image if available |
--compiled-modules={yes*|no|existing|strict} | Enable or disable incremental precompilation of modules. The existing option allows use of existing compiled modules that were previously precompiled, but disallows creation of new precompile files. The strict option is similar, but will error if no precompile file is found. |
--pkgimages={yes*|no|existing} | Enable or disable usage of native code caching in the form of pkgimages. The existing option allows use of existing pkgimages but disallows creation of new ones |
-e , --eval <expr> | Evaluate <expr> |
-E , --print <expr> | Evaluate <expr> and display the result |
-m , --module <Package> [args] | Run entry point of Package (@main function) with `args' |
-L , --load <file> | Load <file> immediately on all processors |
-t , --threads {auto|N[,auto|M]} | Enable N[+M] threads; N threads are assigned to the default threadpool, and if M is specified, M threads are assigned to the interactive threadpool; auto tries to infer a useful default number of threads to use but the exact behavior might change in the future. Currently sets N to the number of CPUs assigned to this Julia process based on the OS-specific affinity assignment interface if supported (Linux and Windows) or to the number of CPU threads if not supported (MacOS) or if process affinity is not configured, and sets M to 1. |
--gcthreads=N[,M] | Use N threads for the mark phase of GC and M (0 or 1) threads for the concurrent sweeping phase of GC. N is set to half of the number of compute threads and M is set to 0 if unspecified. |
-p , --procs {N|auto} | Integer value N launches N additional local worker processes; auto launches as many workers as the number of local CPU threads (logical cores) |
--machine-file <file> | Run processes on hosts listed in <file> |
-i , --interactive | Interactive mode; REPL runs and isinteractive() is true |
-q , --quiet | Quiet startup: no banner, suppress REPL warnings |
--banner={yes|no|short|auto*} | Enable or disable startup banner |
--color={yes|no|auto*} | Enable or disable color text |
--history-file={yes*|no} | Load or save history |
--depwarn={yes|no*|error} | Enable or disable syntax and method deprecation warnings (error turns warnings into errors) |
--warn-overwrite={yes|no*} | Enable or disable method overwrite warnings |
--warn-scope={yes*|no} | Enable or disable warning for ambiguous top-level scope |
-C , --cpu-target <target> | Limit usage of CPU features up to <target> ; set to help to see the available options |
-O , --optimize={0|1|2*|3} | Set the optimization level (level is 3 if -O is used without a level) ($) |
--min-optlevel={0*|1|2|3} | Set the lower bound on per-module optimization |
-g , --debug-info={0|1*|2} | Set the level of debug info generation (level is 2 if -g is used without a level) ($) |
--inline={yes|no} | Control whether inlining is permitted, including overriding @inline declarations |
--check-bounds={yes|no|auto*} | Emit bounds checks always, never, or respect @inbounds declarations ($) |
--math-mode={ieee,fast} | Disallow or enable unsafe floating point optimizations (overrides @fastmath declaration) |
--polly={yes*|no} | Enable or disable the polyhedral optimizer Polly (overrides @polly declaration) |
--code-coverage[={none*|user|all}] | Count executions of source lines (omitting setting is equivalent to user ) |
--code-coverage=@<path> | Count executions but only in files that fall under the given file path/directory. The @ prefix is required to select this option. A @ with no path will track the current directory. |
--code-coverage=tracefile.info | Append coverage information to the LCOV tracefile (filename supports format tokens). |
--track-allocation[={none*|user|all}] | Count bytes allocated by each source line (omitting setting is equivalent to "user") |
--track-allocation=@<path> | Count bytes but only in files that fall under the given file path/directory. The @ prefix is required to select this option. A @ with no path will track the current directory. |
--bug-report=KIND | Launch a bug report session. It can be used to start a REPL, run a script, or evaluate expressions. It first tries to use BugReporting.jl installed in current environment and falls back to the latest compatible BugReporting.jl if not. For more information, see --bug-report=help . |
--heap-size-hint=<size> | Forces garbage collection if memory usage is higher than the given value. The value may be specified as a number of bytes, optionally in units of KB, MB, GB, or TB, or as a percentage of physical memory with %. |
--compile={yes*|no|all|min} | Enable or disable JIT compiler, or request exhaustive or minimal compilation |
--output-o <name> | Generate an object file (including system image data) |
--output-ji <name> | Generate a system image data file (.ji) |
--strip-metadata | Remove docstrings and source location info from system image |
--strip-ir | Remove IR (intermediate representation) of compiled functions |
--output-unopt-bc <name> | Generate unoptimized LLVM bitcode (.bc) |
--output-bc <name> | Generate LLVM bitcode (.bc) |
--output-asm <name> | Generate an assembly file (.s) |
--output-incremental={yes|no*} | Generate an incremental output file (rather than complete) |
--trace-compile={stderr|name} | Print precompile statements for methods compiled during execution or save to a path |
--image-codegen | Force generate code in imaging mode |
--permalloc-pkgimg={yes|no*} | Copy the data section of package images into memory |
En Julia 1.0, la opción predeterminada --project=@.
no buscaba hacia arriba desde el directorio raíz de un repositorio Git para el archivo Project.toml
. A partir de Julia 1.1, sí lo hace.