Janet 1.38.0-73334f3 Documentation
(Other Versions:
1.37.1
1.36.0
1.35.0
1.34.0
1.31.0
1.29.1
1.28.0
1.27.0
1.26.0
1.25.1
1.24.0
1.23.0
1.22.0
1.21.0
1.20.0
1.19.0
1.18.1
1.17.1
1.16.1
1.15.0
1.13.1
1.12.2
1.11.1
1.10.1
1.9.1
1.8.1
1.7.0
1.6.0
1.5.1
1.5.0
1.4.0
1.3.1
)
Executing a Process
In the simpler approach using os/execute
, once the program is
started to create a subprocess, the function does not return or error
until the subprocess has finished executing. Technically,
os/execute
"waits" on the created subprocess. Further details
regarding waiting will be covered when discussing os/spawn
.
The return value for os/execute
is the exit code of the created
subprocess.
args
The only required argument, args
, is a tuple or array of
strings that represents an invocation of a program along with its
arguments.
# prints: I drank what?
# also returns 0, the exit code
(os/execute ["janet" "-e" `(print "I drank what?")`] :p) # => 0
flags
If there is a second argument, flags
, it should be a keyword.
flags
can affect program launching and subprocess execution
characteristics.
Note in the example above, flags
is :p
, which allows
searching the current PATH
for a binary to execute. If
flags
does not contain p
, the name of the program must
be an absolute path.
If flags
contains x
, os/execute
will raise an
error if the subprocess' exit code is non-zero.
# prints: non-zero exit code
(try
(os/execute ["janet" "-e" `(os/exit 1)`] :px)
([_]
(eprint "non-zero exit code")))
env
If flags
contains e
, os/execute
should take a
third argument, env
, a dictionary (i.e. table or struct),
mapping environment variable names to values. The subprocess will be
started using an environment constructed from env
. If
flags
does not contain e
, the current environment is
inherited.
# prints "SITTING"
# also returns 0
(os/execute ["janet" "-e" `(pp (os/getenv "POSE"))`]
:pe {"POSE" "SITTING"}) # => 0
The env
dictionary can also contain the keys :in
,
:out
, and :err
, which allow redirecting standard IO in
the subprocess. The associated values for these keys should be
core/file
values and these should be closed explicitly (e.g. by
calling file/close
) after the subprocess has completed.
Note that the flags
keyword argument only needs to contain
e
if making use of environment variables. That is, for use of
any combination of just :in
, :out
, and :err
, the
flags
keyword does not need to contain e
.
(def of (file/temp))
(os/execute ["janet" "-e" `(print "tada!")`]
:p {:out of}) # => 0
(file/seek of :set 0)
(file/read of :all) # => @"tada!\n"
(file/close of) # => nil
Caveat
Although it may appear to be possible to successfully use
core/stream
values with os/execute
in some cases, it may
not work in certain situations (e.g. with another operating system,
different programs, varied arguments, phase of the moon, etc.). It is
not a reliable choice and is thus not recommended. The
os/spawn
function is better suited for use with
core/stream
values.