Command-line Interface
Using arguments inside scripts
При запуске скрипта с помощью julia
вы можете передать дополнительные аргументы вашему скрипту:
$ julia script.jl arg1 arg2...
Эти дополнительные аргументы командной строки передаются в глобальную константу ARGS
. Имя самого скрипта передается как глобальная переменная PROGRAM_FILE
. Обратите внимание, что ARGS
также устанавливается, когда выражение Julia передается с помощью опции -e
в командной строке (см. вывод справки julia
ниже), но PROGRAM_FILE
будет пустым. Например, чтобы просто вывести аргументы, переданные скрипту, вы можете сделать следующее:
$ julia -e 'println(PROGRAM_FILE); for x in ARGS; println(x); end' foo bar
foo
bar
Или вы можете поместить этот код в скрипт и запустить его:
$ echo 'println(PROGRAM_FILE); for x in ARGS; println(x); end' > script.jl
$ julia script.jl foo bar
script.jl
foo
bar
Делимитер --
может быть использован для разделения аргументов командной строки, предназначенных для файла скрипта, от аргументов, предназначенных для Julia:
$ julia --color=yes -O -- script.jl arg1 arg2..
Смотрите также Scripting для получения дополнительной информации о написании скриптов на Julia.
The Main.main
entry point
Начиная с Julia 1.11, Base
экспортирует макрос @main
. Этот макрос расширяется до символа main
, но по завершении выполнения скрипта или выражения julia
попытается выполнить функцию Main.main(ARGS)
, если такая функция была определена и это поведение было выбрано с помощью макроса @main
.
Эта функция предназначена для помощи в унификации скомпилированных и интерактивных рабочих процессов. В скомпилированных рабочих процессах загрузка кода, который определяет функцию main
, может быть пространственно и временно отделена от вызова. Однако для интерактивных рабочих процессов поведение эквивалентно явному вызову exit(main(ARGS))
в конце оцененного скрипта или выражения.
Специальная точка входа Main.main
была добавлена в Julia 1.11. Для совместимости с предыдущими версиями Julia добавьте явное @isdefined(var"@main") ? (@main) : exit(main(ARGS))
в конце ваших скриптов.
Чтобы увидеть эту функцию в действии, рассмотрите следующее определение, которое выполнит функцию print, несмотря на отсутствие явного вызова main
:
$ julia -e '(@main)(args) = println("Hello World!")'
Hello World!
$
Только привязка main
в модуле Main
имеет такое поведение, и только если макрос @main
был использован в определяющем модуле.
Например, использование hello
вместо main
не приведет к выполнению функции hello
:
$ julia -e 'hello(ARGS) = println("Hello World!")'
$
и простое определение main
тоже не поможет:
$ julia -e 'main(ARGS) = println("Hello World!")'
$
Однако, согласие не обязательно должно происходить во время определения:
$ julia -e 'main(ARGS) = println("Hello World!"); @main'
Hello World!
$
Связывание main
может быть импортировано из пакета. Пакет hello world, определенный как
module Hello
export main
(@main)(args) = println("Hello from the package!")
end
может использоваться как:
$ 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
$
Однако обратите внимание, что текущая рекомендация по лучшим практикам заключается в том, чтобы не смешивать код приложения и кода повторно используемой библиотеки в одном пакете. Вспомогательные приложения могут распространяться как отдельные пакеты или как скрипты с отдельными точками входа main
в папке bin
пакета.
Parallel mode
Julia можно запустить в параллельном режиме с помощью параметров -p
или --machine-file
. -p n
запустит дополнительно n
рабочих процессов, в то время как --machine-file file
запустит рабочего для каждой строки в файле file
. Машины, определенные в file
, должны быть доступны через вход без пароля по ssh
, с установленным Julia в том же месте, что и текущий хост. Каждое определение машины имеет форму [count*][user@]host[:port] [bind_addr[:port]]
. user
по умолчанию равен текущему пользователю, port
— стандартному порту ssh. count
— это количество рабочих, которые нужно запустить на узле, и по умолчанию равно 1. Необязательный bind-to bind_addr[:port]
указывает IP-адрес и порт, которые другие рабочие должны использовать для подключения к этому рабочему.
Startup file
Если у вас есть код, который вы хотите выполнить каждый раз при запуске Julia, вы можете поместить его в ~/.julia/config/startup.jl
:
$ echo 'println("Greetings! 你好! 안녕하세요?")' > ~/.julia/config/startup.jl
$ julia
Greetings! 你好! 안녕하세요?
...
Обратите внимание, что хотя у вас должна быть директория ~/.julia
после первого запуска Julia, вам может потребоваться создать папку ~/.julia/config
и файл ~/.julia/config/startup.jl
, если вы собираетесь его использовать.
Чтобы код инициализации выполнялся только в The Julia REPL (и не при запуске julia
, например, на скрипте), используйте atreplinit
в startup.jl
:
atreplinit() do repl
# ...
end
Command-line switches for Julia
Существует несколько способов запуска кода на Julia и предоставления опций, аналогичных тем, что доступны для программ perl
и ruby
:
julia [switches] -- [programfile] [args...]
Следующий список содержит все доступные параметры командной строки при запуске julia (звездочка '*' обозначает значение по умолчанию, если применимо; настройки, отмеченные '($)', могут вызвать предкомпиляцию пакетов):
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 |
В Julia 1.0 параметр по умолчанию --project=@.
не искал файл Project.toml
в корневом каталоге репозитория Git. Начиная с Julia 1.1, он это делает.