Command-line Interface

Using arguments inside scripts

Beim Ausführen eines Skripts mit julia können Sie zusätzliche Argumente an Ihr Skript übergeben:

$ julia script.jl arg1 arg2...

Diese zusätzlichen Befehlszeilenargumente werden in der globalen Konstante ARGS übergeben. Der Name des Skripts selbst wird als globale PROGRAM_FILE übergeben. Beachten Sie, dass ARGS auch gesetzt wird, wenn ein Julia-Ausdruck mit der -e-Option in der Befehlszeile angegeben wird (siehe die Hilfeausgabe von julia unten), aber PROGRAM_FILE wird leer sein. Zum Beispiel, um einfach die an ein Skript übergebenen Argumente auszugeben, könnten Sie Folgendes tun:

$ julia -e 'println(PROGRAM_FILE); for x in ARGS; println(x); end' foo bar

foo
bar

Oder du könntest diesen Code in ein Skript einfügen und ausführen:

$ echo 'println(PROGRAM_FILE); for x in ARGS; println(x); end' > script.jl
$ julia script.jl foo bar
script.jl
foo
bar

Der -- Trennzeichen kann verwendet werden, um Befehlszeilenargumente, die für die Skriptdatei bestimmt sind, von Argumenten zu trennen, die für Julia bestimmt sind:

$ julia --color=yes -O -- script.jl arg1 arg2..

Siehe auch Scripting für weitere Informationen zum Schreiben von Julia-Skripten.

The Main.main entry point

Ab Julia 1.11 exportiert Base das Makro @main. Dieses Makro erweitert sich zu dem Symbol main, aber am Ende der Ausführung eines Skripts oder Ausdrucks wird julia versuchen, die Funktion Main.main(ARGS) auszuführen, wenn eine solche Funktion definiert wurde und dieses Verhalten durch die Verwendung des Makros @main aktiviert wurde.

Dieses Feature soll bei der Vereinheitlichung von kompilierten und interaktiven Workflows helfen. In kompilierten Workflows kann das Laden des Codes, der die main-Funktion definiert, räumlich und zeitlich von der Aufrufung getrennt sein. Bei interaktiven Workflows hingegen entspricht das Verhalten dem expliziten Aufruf von exit(main(ARGS)) am Ende des ausgewerteten Skripts oder Ausdrucks.

Julia 1.11

Der spezielle Einstiegspunkt Main.main wurde in Julia 1.11 hinzugefügt. Um die Kompatibilität mit früheren Julia-Versionen zu gewährleisten, fügen Sie am Ende Ihrer Skripte eine explizite @isdefined(var"@main") ? (@main) : exit(main(ARGS)) hinzu.

Um diese Funktion in Aktion zu sehen, betrachten Sie die folgende Definition, die die Druckfunktion ausführt, obwohl es keinen expliziten Aufruf von main gibt:

$ julia -e '(@main)(args) = println("Hello World!")'
Hello World!
$

Nur die main-Bindung im Main-Modul hat dieses Verhalten und nur, wenn das Makro @main innerhalb des definierenden Moduls verwendet wurde.

Zum Beispiel wird die Verwendung von hello anstelle von main nicht dazu führen, dass die hello-Funktion ausgeführt wird:

$ julia -e 'hello(ARGS) = println("Hello World!")'
$

und auch eine einfache Definition von main wird es nicht tun:

$ julia -e 'main(ARGS) = println("Hello World!")'
$

Es ist jedoch nicht erforderlich, dass die Zustimmung zum Zeitpunkt der Definition erfolgt:

$ julia -e 'main(ARGS) = println("Hello World!"); @main'
Hello World!
$

Die main-Bindung kann aus einem Paket importiert werden. Ein Hallo Welt Paket, das definiert ist als

module Hello

export main
(@main)(args) = println("Hello from the package!")

end

kann verwendet werden als:

$ 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
$

Beachten Sie jedoch, dass die aktuelle Empfehlung der besten Praxis darin besteht, Anwendungs- und wiederverwendbare Bibliothekscodes nicht im selben Paket zu mischen. Hilfsanwendungen können als separate Pakete oder als Skripte mit separaten main-Einstiegspunkten im bin-Ordner eines Pakets verteilt werden.

Parallel mode

Julia kann im Parallelmodus mit den Optionen -p oder --machine-file gestartet werden. -p n startet zusätzlich n Arbeitsprozesse, während --machine-file file einen Arbeiter für jede Zeile in der Datei file startet. Die in file definierten Maschinen müssen über einen passwortlosen ssh-Login zugänglich sein, wobei Julia am gleichen Ort wie der aktuelle Host installiert sein muss. Jede Maschinenbeschreibung hat die Form [count*][user@]host[:port] [bind_addr[:port]]. user ist standardmäßig der aktuelle Benutzer, port der Standard-ssh-Port. count ist die Anzahl der Arbeiter, die auf dem Knoten gestartet werden sollen, und beträgt standardmäßig 1. Die optionale bind-to bind_addr[:port] gibt die IP-Adresse und den Port an, die andere Arbeiter verwenden sollen, um sich mit diesem Arbeiter zu verbinden.

Startup file

Wenn Sie Code haben, der jedes Mal ausgeführt werden soll, wenn Julia gestartet wird, können Sie ihn in ~/.julia/config/startup.jl einfügen:

$ echo 'println("Greetings! 你好! 안녕하세요?")' > ~/.julia/config/startup.jl
$ julia
Greetings! 你好! 안녕하세요?

...

Beachten Sie, dass Sie zwar ein ~/.julia-Verzeichnis haben sollten, sobald Sie Julia zum ersten Mal ausgeführt haben, Sie jedoch möglicherweise den ~/.julia/config-Ordner und die Datei ~/.julia/config/startup.jl erstellen müssen, wenn Sie sie verwenden.

Um den Startcode nur in The Julia REPL auszuführen (und nicht, wenn julia z. B. in einem Skript ausgeführt wird), verwenden Sie atreplinit in startup.jl:

atreplinit() do repl
    # ...
end

Command-line switches for Julia

Es gibt verschiedene Möglichkeiten, Julia-Code auszuführen und Optionen bereitzustellen, ähnlich wie bei den Programmen perl und ruby:

julia [switches] -- [programfile] [args...]

Die folgende ist eine vollständige Liste der Befehlszeilenoptionen, die beim Starten von Julia verfügbar sind (ein '*' kennzeichnet den Standardwert, falls zutreffend; Einstellungen, die mit '($)' gekennzeichnet sind, können die Vorabkompilierung von Paketen auslösen):

SwitchDescription
-v, --versionDisplay version information
-h, --helpPrint command-line options (this message)
--help-hiddenPrint 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, --interactiveInteractive mode; REPL runs and isinteractive() is true
-q, --quietQuiet 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.infoAppend 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=KINDLaunch 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-metadataRemove docstrings and source location info from system image
--strip-irRemove 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-codegenForce generate code in imaging mode
--permalloc-pkgimg={yes|no*}Copy the data section of package images into memory
Julia 1.1

In Julia 1.0 suchte die Standardoption --project=@. nicht vom Stammverzeichnis eines Git-Repositorys nach der Datei Project.toml. Ab Julia 1.1 tut sie dies.