Base.stdout —ConstantBase.stderr —ConstantBase.stdin —ConstantBase.read —Methodread(filename::AbstractString)Read the entire contents of a file as aVector{UInt8}.
read(filename::AbstractString, String)Read the entire contents of a file as a string.
read(filename::AbstractString, args...)Open a file and read its contents.args is passed toread: this is equivalent toopen(io->read(io, args...), filename).
Base.write —Methodwrite(filename::AbstractString, content)Write the canonical binary representation ofcontent to a file, which will be created if it does not exist yet or overwritten if it does exist.
Return the number of bytes written into the file.
sourceBase.open —Functionopen(f::Function, command, args...; kwargs...)Similar toopen(command, args...; kwargs...), but callsf(stream) on the resulting process stream, then closes the input stream and waits for the process to complete. Return the value returned byf on success. Throw an error if the process failed, or if the process attempts to print anything to stdout.
open(command, stdio=devnull; write::Bool = false, read::Bool = !write)Start runningcommand asynchronously, and return aprocess::IO object. Ifread is true, then reads from the process come from the process's standard output andstdio optionally specifies the process's standard input stream. Ifwrite is true, then writes go to the process's standard input andstdio optionally specifies the process's standard output stream. The process's standard error stream is connected to the current globalstderr.
open(command, mode::AbstractString, stdio=devnull)Runcommand asynchronously. Likeopen(command, stdio; read, write) except specifying the read and write flags via a mode string instead of keyword arguments. Possible mode strings are:
| Mode | Description | Keywords |
|---|---|---|
r | read | none |
w | write | write = true |
r+ | read, write | read = true, write = true |
w+ | read, write | read = true, write = true |
open(fd::OS_HANDLE) -> IOTake a raw file descriptor wrap it in a Julia-aware IO type, and take ownership of the fd handle. Callopen(Libc.dup(fd)) to avoid the ownership capture of the original handle.
open(filename::AbstractString, [mode::AbstractString]; lock = true) -> IOStreamAlternate syntax for open, where a string-based mode specifier is used instead of the five booleans. The values ofmode correspond to those fromfopen(3) or Perlopen, and are equivalent to setting the following boolean groups:
| Mode | Description | Keywords |
|---|---|---|
r | read | none |
w | write, create, truncate | write = true |
a | write, create, append | append = true |
r+ | read, write | read = true, write = true |
w+ | read, write, create, truncate | truncate = true, read = true |
a+ | read, write, create, append | append = true, read = true |
Thelock keyword argument controls whether operations will be locked for safe multi-threaded access.
Examples
julia> io = open("myfile.txt", "w");julia> write(io, "Hello world!");julia> close(io);julia> io = open("myfile.txt", "r");julia> read(io, String)"Hello world!"julia> write(io, "This file is read only")ERROR: ArgumentError: write failed, IOStream is not writeable[...]julia> close(io)julia> io = open("myfile.txt", "a");julia> write(io, "This stream is not read only")28julia> close(io)julia> rm("myfile.txt")sourceopen(filename::AbstractString; lock = true, keywords...) -> IOStreamOpen a file in a mode specified by five boolean keyword arguments:
| Keyword | Description | Default |
|---|---|---|
read | open for reading | !write |
write | open for writing | truncate | append |
create | create if non-existent | !read & write | truncate | append |
truncate | truncate to zero size | !read & write |
append | seek to end | false |
The default when no keywords are passed is to open files for reading only. Returns a stream for accessing the opened file.
Thelock keyword argument controls whether operations will be locked for safe multi-threaded access.
open(f::Function, args...; kwargs...)Apply the functionf to the result ofopen(args...; kwargs...) and close the resulting file descriptor upon completion.
Examples
julia> write("myfile.txt", "Hello world!");julia> open(io->read(io, String), "myfile.txt")"Hello world!"julia> rm("myfile.txt")sourceBase.IOStream —TypeBase.IOBuffer —TypeIOBuffer(string::String)Create a read-onlyIOBuffer on the data underlying the given string.
Examples
julia> io = IOBuffer("Haho");julia> String(take!(io))"Haho"julia> String(take!(io))"Haho"sourceIOBuffer([data::AbstractVector{UInt8}]; keywords...) -> IOBufferCreate an in-memory I/O stream, which may optionally operate on a pre-existing array.
It may take optional keyword arguments:
read,write,append: restricts operations to the buffer; seeopen for details.truncate: truncates the buffer size to zero length.maxsize: specifies a size beyond which the buffer may not be grown.sizehint: suggests a capacity of the buffer (data must implementsizehint!(data, size)).Whendata is not given, the buffer will be both readable and writable by default.
Oncewrite is called on anIOBuffer, it is best to consider any previous references todata invalidated; in effectIOBuffer "owns" this data until a call totake!. Any indirect mutations todata could lead to undefined behavior by breaking the abstractions expected byIOBuffer. Ifwrite=true the IOBuffer may store data at any offset leaving behind arbitrary values at other offsets. Ifmaxsize > length(data), the IOBuffer might re-allocate the data entirely, which may or may not be visible in any outstanding bindings toarray.
Examples
julia> io = IOBuffer();julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")56julia> String(take!(io))"JuliaLang is a GitHub organization. It has many members."julia> io = IOBuffer(b"JuliaLang is a GitHub organization.")IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=35, maxsize=Inf, ptr=1, mark=-1)julia> read(io, String)"JuliaLang is a GitHub organization."julia> write(io, "This isn't writable.")ERROR: ArgumentError: ensureroom failed, IOBuffer is not writeablejulia> io = IOBuffer(UInt8[], read=true, write=true, maxsize=34)IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=34, ptr=1, mark=-1)julia> write(io, "JuliaLang is a GitHub organization.")34julia> String(take!(io))"JuliaLang is a GitHub organization"julia> length(read(IOBuffer(b"data", read=true, truncate=false)))4julia> length(read(IOBuffer(b"data", read=true, truncate=true)))0sourceBase.take! —Methodtake!(b::IOBuffer)Obtain the contents of anIOBuffer as an array. Afterwards, theIOBuffer is reset to its initial state.
Examples
julia> io = IOBuffer();julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")56julia> String(take!(io))"JuliaLang is a GitHub organization. It has many members."sourceBase.Pipe —TypePipe()Construct an uninitialized Pipe object, especially for IO communication between multiple processes.
The appropriate end of the pipe will be automatically initialized if the object is used in process spawning. This can be useful to easily obtain references in process pipelines, e.g.:
julia> err = Pipe()# After this `err` will be initialized and you may read `foo`'s# stderr from the `err` pipe, or pass `err` to other pipelines.julia> run(pipeline(pipeline(`foo`, stderr=err), `cat`), wait=false)# Now destroy the write half of the pipe, so that the read half will get EOFjulia> closewrite(err)julia> read(err, String)"stderr messages"See alsoBase.link_pipe!.
Base.link_pipe! —Functionlink_pipe!(pipe; reader_supports_async=false, writer_supports_async=false)Initializepipe and link thein endpoint to theout endpoint. The keyword argumentsreader_supports_async/writer_supports_async correspond toOVERLAPPED on Windows andO_NONBLOCK on POSIX systems. They should betrue unless they'll be used by an external program (e.g. the output of a command executed withrun).
Base.fdio —Functionfdio([name::AbstractString, ]fd::Integer[, own::Bool=false]) -> IOStreamCreate anIOStream object from an integer file descriptor. Ifown istrue, closing this object will close the underlying descriptor. By default, anIOStream is closed when it is garbage collected.name allows you to associate the descriptor with a named file.
Base.flush —FunctionBase.close —FunctionBase.closewrite —Functionclosewrite(stream)Shutdown the write half of a full-duplex I/O stream. Performs aflush first. Notify the other end that no more data will be written to the underlying file. This is not supported by all IO types.
If implemented,closewrite causes subsequentread oreof calls that would block to instead throw EOF or return true, respectively. If the stream is already closed, this is idempotent.
Examples
julia> io = Base.BufferStream(); # this never blocks, so we can read and write on the same Taskjulia> write(io, "request");julia> # calling `read(io)` here would block foreverjulia> closewrite(io);julia> read(io, String)"request"sourceBase.write —Functionwrite(io::IO, x)Write the canonical binary representation of a value to the given I/O stream or file. Return the number of bytes written into the stream. See alsoprint to write a text representation (with an encoding that may depend uponio).
The endianness of the written value depends on the endianness of the host system. Convert to/from a fixed endianness when writing/reading (e.g. usinghtol andltoh) to get results that are consistent across platforms.
You can write multiple values with the samewrite call, i.e. the following are equivalent:
write(io, x, y...)write(io, x) + write(io, y...)Examples
Consistent serialization:
julia> fname = tempname(); # random temporary filenamejulia> open(fname,"w") do f # Make sure we write 64bit integer in little-endian byte order write(f,htol(Int64(42))) end8julia> open(fname,"r") do f # Convert back to host byte order and host integer type Int(ltoh(read(f,Int64))) end42Merging write calls:
julia> io = IOBuffer();julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")56julia> String(take!(io))"JuliaLang is a GitHub organization. It has many members."julia> write(io, "Sometimes those members") + write(io, " write documentation.")44julia> String(take!(io))"Sometimes those members write documentation."User-defined plain-data types withoutwrite methods can be written when wrapped in aRef:
julia> struct MyStruct; x::Float64; endjulia> io = IOBuffer()IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)julia> write(io, Ref(MyStruct(42.0)))8julia> seekstart(io); read!(io, Ref(MyStruct(NaN)))Base.RefValue{MyStruct}(MyStruct(42.0))sourceBase.read —Functionread(s::IOStream, nb::Integer; all=true)Read at mostnb bytes froms, returning aVector{UInt8} of the bytes read.
Ifall istrue (the default), this function will block repeatedly trying to read all requested bytes, until an error or end-of-file occurs. Ifall isfalse, at most oneread call is performed, and the amount of data returned is device-dependent. Note that not all stream types support theall option.
read(s::IO, nb=typemax(Int))Read at mostnb bytes froms, returning aVector{UInt8} of the bytes read.
read(filename::AbstractString)Read the entire contents of a file as aVector{UInt8}.
read(filename::AbstractString, String)Read the entire contents of a file as a string.
read(filename::AbstractString, args...)Open a file and read its contents.args is passed toread: this is equivalent toopen(io->read(io, args...), filename).
read(io::IO, T)Read a single value of typeT fromio, in canonical binary representation.
Note that Julia does not convert the endianness for you. Usentoh orltoh for this purpose.
read(io::IO, String)Read the entirety ofio, as aString (see alsoreadchomp).
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization");julia> read(io, Char)'J': ASCII/Unicode U+004A (category Lu: Letter, uppercase)julia> io = IOBuffer("JuliaLang is a GitHub organization");julia> read(io, String)"JuliaLang is a GitHub organization"sourceBase.read! —Functionread!(stream::IO, array::AbstractArray)read!(filename::AbstractString, array::AbstractArray)Read binary data from an I/O stream or file, filling inarray.
Base.readbytes! —Functionreadbytes!(stream::IOStream, b::AbstractVector{UInt8}, nb=length(b); all::Bool=true)Read at mostnb bytes fromstream intob, returning the number of bytes read. The size ofb will be increased if needed (i.e. ifnb is greater thanlength(b) and enough bytes could be read), but it will never be decreased.
Ifall istrue (the default), this function will block repeatedly trying to read all requested bytes, until an error or end-of-file occurs. Ifall isfalse, at most oneread call is performed, and the amount of data returned is device-dependent. Note that not all stream types support theall option.
readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b))Read at mostnb bytes fromstream intob, returning the number of bytes read. The size ofb will be increased if needed (i.e. ifnb is greater thanlength(b) and enough bytes could be read), but it will never be decreased.
Base.unsafe_read —Functionunsafe_read(io::IO, ref, nbytes::UInt)Copynbytes from theIO stream object intoref (converted to a pointer).
It is recommended that subtypesT<:IO override the following method signature to provide more efficient implementations:unsafe_read(s::T, p::Ptr{UInt8}, n::UInt)
Base.unsafe_write —Functionunsafe_write(io::IO, ref, nbytes::UInt)Copynbytes fromref (converted to a pointer) into theIO object.
It is recommended that subtypesT<:IO override the following method signature to provide more efficient implementations:unsafe_write(s::T, p::Ptr{UInt8}, n::UInt)
Base.readeach —Functionreadeach(io::IO, T)Return an iterable object yieldingread(io, T).
See alsoskipchars,eachline,readuntil.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization.\n It has many members.\n");julia> for c in readeach(io, Char) c == '\n' && break print(c) endJuliaLang is a GitHub organization.sourceBase.peek —Functionpeek(stream[, T=UInt8])Read and return a value of typeT from a stream without advancing the current position in the stream. See alsostartswith(stream, char_or_string).
Examples
julia> b = IOBuffer("julia");julia> peek(b)0x6ajulia> position(b)0julia> peek(b, Char)'j': ASCII/Unicode U+006A (category Ll: Letter, lowercase)sourceBase.position —Functionposition(s)Get the current position of a stream.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization.");julia> seek(io, 5);julia> position(io)5julia> skip(io, 10);julia> position(io)15julia> seekend(io);julia> position(io)35sourceBase.seekstart —Functionseekstart(s)Seek a stream to its beginning.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization.");julia> seek(io, 5);julia> read(io, Char)'L': ASCII/Unicode U+004C (category Lu: Letter, uppercase)julia> seekstart(io);julia> read(io, Char)'J': ASCII/Unicode U+004A (category Lu: Letter, uppercase)sourceBase.seekend —FunctionBase.unmark —FunctionBase.reset —MethodBase.ismarked —FunctionBase.eof —Functioneof(stream) -> BoolTest whether an I/O stream is at end-of-file. If the stream is not yet exhausted, this function will block to wait for more data if necessary, and then returnfalse. Therefore it is always safe to read one byte after seeingeof returnfalse.eof will returnfalse as long as buffered data is still available, even if the remote end of a connection is closed.
Examples
julia> b = IOBuffer("my buffer");julia> eof(b)falsejulia> seekend(b);julia> eof(b)truesourceBase.isreadonly —Functionisreadonly(io) -> BoolDetermine whether a stream is read-only.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization");julia> isreadonly(io)truejulia> io = IOBuffer();julia> isreadonly(io)falsesourceBase.iswritable —Functioniswritable(path::String)Returntrue if the access permissions for the givenpath permitted writing by the current user.
This permission may change before the user callsopen, so it is recommended to just callopen alone and handle the error if that fails, rather than callingiswritable first.
Currently this function does not correctly interrogate filesystem ACLs on Windows, therefore it can return wrong results.
See alsoispath,isexecutable,isreadable.
iswritable(io) -> BoolReturnfalse if the specified IO object is not writable.
Examples
julia> open("myfile.txt", "w") do io print(io, "Hello world!"); iswritable(io) endtruejulia> open("myfile.txt", "r") do io iswritable(io) endfalsejulia> rm("myfile.txt")sourceBase.isreadable —Functionisreadable(path::String)Returntrue if the access permissions for the givenpath permitted reading by the current user.
This permission may change before the user callsopen, so it is recommended to just callopen alone and handle the error if that fails, rather than callingisreadable first.
Currently this function does not correctly interrogate filesystem ACLs on Windows, therefore it can return wrong results.
See alsoispath,isexecutable,iswritable.
isreadable(io) -> BoolReturnfalse if the specified IO object is not readable.
Examples
julia> open("myfile.txt", "w") do io print(io, "Hello world!"); isreadable(io) endfalsejulia> open("myfile.txt", "r") do io isreadable(io) endtruejulia> rm("myfile.txt")sourceBase.isexecutable —Functionisexecutable(path::String)Returntrue if the givenpath has executable permissions.
This permission may change before the user executespath, so it is recommended to execute the file and handle the error if that fails, rather than callingisexecutable first.
Prior to Julia 1.6, this did not correctly interrogate filesystem ACLs on Windows, therefore it would returntrue for any file. From Julia 1.6 on, it correctly determines whether the file is marked as executable or not.
See alsoispath,isreadable,iswritable.
Base.isopen —Functionisopen(object) -> BoolDetermine whether an object - such as a stream or timer – is not yet closed. Once an object is closed, it will never produce a new event. However, since a closed stream may still have data to read in its buffer, useeof to check for the ability to read data. Use theFileWatching package to be notified when a stream might be writable or readable.
Examples
julia> io = open("my_file.txt", "w+");julia> isopen(io)truejulia> close(io)julia> isopen(io)falsesourceBase.fd —Functionfd(x) -> RawFDReturn the file descriptor backing the stream, file, or socket.
RawFD objects can be passed directly to other languages via theccall interface.
Prior to 1.12, this function returned anInt instead of aRawFD. You may useRawFD(fd(x)) to produce aRawFD in all Julia versions.
Duplicate the returned file descriptor withLibc.dup() before passing it to another system that will take ownership of it (e.g. a C library). Otherwise both the Julia objectx and the other system may try to close the file descriptor, which will cause errors.
The file descriptors for sockets are asynchronous (i.e.O_NONBLOCK on POSIX andOVERLAPPED on Windows), they may behave differently than regular file descriptors.
Base.redirect_stdio —Functionredirect_stdio(f; stdin=nothing, stderr=nothing, stdout=nothing)Redirect a subset of the streamsstdin,stderr,stdout, callf() and restore each stream.
Possible values for each stream are:
nothing indicating the stream should not be redirected.path::AbstractString redirecting the stream to the file atpath.io anIOStream,TTY,Pipe, socket, ordevnull.Examples
julia> redirect_stdio(stdout="stdout.txt", stderr="stderr.txt") do print("hello stdout") print(stderr, "hello stderr") endjulia> read("stdout.txt", String)"hello stdout"julia> read("stderr.txt", String)"hello stderr"Edge cases
It is possible to pass the same argument tostdout andstderr:
julia> redirect_stdio(stdout="log.txt", stderr="log.txt", stdin=devnull) do ...endHowever it is not supported to pass two distinct descriptors of the same file.
julia> io1 = open("same/path", "w")julia> io2 = open("same/path", "w")julia> redirect_stdio(f, stdout=io1, stderr=io2) # not supportedAlso thestdin argument may not be the same descriptor asstdout orstderr.
julia> io = open(...)julia> redirect_stdio(f, stdout=io, stdin=io) # not supportedsourceBase.redirect_stdout —Functionredirect_stdout([stream]) -> streamCreate a pipe to which all C and Julia levelstdout output will be redirected. Return a stream representing the pipe ends. Data written tostdout may now be read from therd end of the pipe.
stream must be a compatible objects, such as anIOStream,TTY,Pipe, socket, ordevnull.
See alsoredirect_stdio.
Base.redirect_stdout —MethodBase.redirect_stderr —Functionredirect_stderr([stream]) -> streamLikeredirect_stdout, but forstderr.
stream must be a compatible objects, such as anIOStream,TTY,Pipe, socket, ordevnull.
See alsoredirect_stdio.
Base.redirect_stderr —MethodBase.redirect_stdin —Functionredirect_stdin([stream]) -> streamLikeredirect_stdout, but forstdin. Note that the direction of the stream is reversed.
stream must be a compatible objects, such as anIOStream,TTY,Pipe, socket, ordevnull.
See alsoredirect_stdio.
Base.redirect_stdin —MethodBase.readchomp —Functionreadchomp(x)Read the entirety ofx as a string and remove a single trailing newline if there is one. Equivalent tochomp(read(x, String)).
Examples
julia> write("my_file.txt", "JuliaLang is a GitHub organization.\nIt has many members.\n");julia> readchomp("my_file.txt")"JuliaLang is a GitHub organization.\nIt has many members."julia> rm("my_file.txt");sourceBase.truncate —Functiontruncate(file, n)Resize the file or buffer given by the first argument to exactlyn bytes, filling previously unallocated space with '\0' if the file or buffer is grown.
Examples
julia> io = IOBuffer();julia> write(io, "JuliaLang is a GitHub organization.")35julia> truncate(io, 15)IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=15, maxsize=Inf, ptr=16, mark=-1)julia> String(take!(io))"JuliaLang is a "julia> io = IOBuffer();julia> write(io, "JuliaLang is a GitHub organization.");julia> truncate(io, 40);julia> String(take!(io))"JuliaLang is a GitHub organization.\0\0\0\0\0"sourceBase.skipchars —Functionskipchars(predicate, io::IO; linecomment=nothing)Advance the streamio such that the next-read character will be the first remaining for whichpredicate returnsfalse. If the keyword argumentlinecomment is specified, all characters from that character until the start of the next line are ignored.
Examples
julia> buf = IOBuffer(" text")IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=8, maxsize=Inf, ptr=1, mark=-1)julia> skipchars(isspace, buf)IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=8, maxsize=Inf, ptr=5, mark=-1)julia> String(readavailable(buf))"text"sourceBase.countlines —Functioncountlines(io::IO; eol::AbstractChar = '\n')countlines(filename::AbstractString; eol::AbstractChar = '\n')Readio until the end of the stream/file and count the number of lines. To specify a file pass the filename as the first argument. EOL markers other than'\n' are supported by passing them as the second argument. The last non-empty line ofio is counted even if it does not end with the EOL, matching the length returned byeachline andreadlines.
To count lines of aString,countlines(IOBuffer(str)) can be used.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization.\n");julia> countlines(io)1julia> io = IOBuffer("JuliaLang is a GitHub organization.");julia> countlines(io)1julia> eof(io) # counting lines moves the file pointertruejulia> io = IOBuffer("JuliaLang is a GitHub organization.");julia> countlines(io, eol = '.')1julia> write("my_file.txt", "JuliaLang is a GitHub organization.\n")36julia> countlines("my_file.txt")1julia> countlines("my_file.txt", eol = 'n')4julia> rm("my_file.txt")sourceBase.PipeBuffer —FunctionPipeBuffer(data::AbstractVector{UInt8}=UInt8[]; maxsize::Integer = typemax(Int))AnIOBuffer that allows reading and performs writes by appending. Seeking and truncating are not supported. SeeIOBuffer for the available constructors. Ifdata is given, creates aPipeBuffer to operate on a data vector, optionally specifying a size beyond which the underlyingArray may not be grown.
Base.readavailable —Functionreadavailable(stream)Read available buffered data from a stream. Actual I/O is performed only if no data has already been buffered. The result is aVector{UInt8}.
The amount of data returned is implementation-dependent; for example it can depend on the internal choice of buffer size. Other functions such asread should generally be used instead.
Base.IOContext —TypeBase.IOContext —MethodIOContext(io::IO, KV::Pair...)Create anIOContext that wraps a given stream, adding the specifiedkey=>value pairs to the properties of that stream (note thatio can itself be anIOContext).
(key => value) in io to see if this particular combination is in the properties setget(io, key, default) to retrieve the most recent value for a particular keyThe following properties are in common use:
:compact: Boolean specifying that values should be printed more compactly, e.g. that numbers should be printed with fewer digits. This is set when printing array elements.:compact output should not contain line breaks.:limit: Boolean specifying that containers should be truncated, e.g. showing… in place of most elements.:displaysize: ATuple{Int,Int} giving the size in rows and columns to use for text output. This can be used to override the display size for called functions, but to get the size of the screen use thedisplaysize function.:typeinfo: aType characterizing the information already printed concerning the type of the object about to be displayed. This is mainly useful when displaying a collection of objects of the same type, so that redundant type information can be avoided (e.g.[Float16(0)] can be shown as "Float16[0.0]" instead of "Float16[Float16(0.0)]" : while displaying the elements of the array, the:typeinfo property will be set toFloat16).:color: Boolean specifying whether ANSI color/escape codes are supported/expected. By default, this is determined by whetherio is a compatible terminal and by any--color command-line flag whenjulia was launched.Examples
julia> io = IOBuffer();julia> printstyled(IOContext(io, :color => true), "string", color=:red)julia> String(take!(io))"\e[31mstring\e[39m"julia> printstyled(io, "string", color=:red)julia> String(take!(io))"string"julia> print(IOContext(stdout, :compact => false), 1.12341234)1.12341234julia> print(IOContext(stdout, :compact => true), 1.12341234)1.12341julia> function f(io::IO) if get(io, :short, false) print(io, "short") else print(io, "loooooong") end endf (generic function with 1 method)julia> f(stdout)loooooongjulia> f(IOContext(stdout, :short => true))shortsourceBase.IOContext —MethodIOContext(io::IO, context::IOContext)Create anIOContext that wraps an alternateIO but inherits the properties ofcontext.
Unless explicitly set in the wrappedio thedisplaysize ofio will not be inherited. This is because by defaultdisplaysize is not a property of IO objects themselves, but lazily inferred, as the size of the terminal window can change during the lifetime of the IO object.
Base.show —Methodshow([io::IO = stdout], x)Write a text representation of a valuex to the output streamio. New typesT should overloadshow(io::IO, x::T). The representation used byshow generally includes Julia-specific formatting and type information, and should be parseable Julia code when possible.
repr returns the output ofshow as a string.
For a more verbose human-readable text output for objects of typeT, defineshow(io::IO, ::MIME"text/plain", ::T) in addition. Checking the:compactIOContext key (often checked asget(io, :compact, false)::Bool) ofio in such methods is recommended, since some containers show their elements by calling this method with:compact => true.
See alsoprint, which writes un-decorated representations.
Examples
julia> show("Hello World!")"Hello World!"julia> print("Hello World!")Hello World!sourceBase.summary —Functionsummary(io::IO, x)str = summary(x)Print to a streamio, or return a stringstr, giving a brief description of a value. By default returnsstring(typeof(x)), e.g.Int64.
For arrays, returns a string of size and type info, e.g.10-element Vector{Int64} or9×4×5 Array{Float64, 3}.
Examples
julia> summary(1)"Int64"julia> summary(zeros(2))"2-element Vector{Float64}"sourceBase.print —Functionprint([io::IO], xs...)Write toio (or to the default output streamstdout ifio is not given) a canonical (un-decorated) text representation. The representation used byprint includes minimal formatting and tries to avoid Julia-specific details.
print falls back to calling the 2-argumentshow(io, x) for each argumentx inxs, so most types should just defineshow. Defineprint if your type has a separate "plain" representation. For example,show displays strings with quotes, andprint displays strings without quotes.
See alsoprintln,string,printstyled.
Examples
julia> print("Hello World!")Hello World!julia> io = IOBuffer();julia> print(io, "Hello", ' ', :World!)julia> String(take!(io))"Hello World!"sourceBase.println —Functionprintln([io::IO], xs...)Print (usingprint)xs toio followed by a newline. Ifio is not supplied, prints to the default output streamstdout.
See alsoprintstyled to add colors etc.
Examples
julia> println("Hello, world")Hello, worldjulia> io = IOBuffer();julia> println(io, "Hello", ',', " world.")julia> String(take!(io))"Hello, world.\n"sourceBase.printstyled —Functionprintstyled([io], xs...; bold::Bool=false, italic::Bool=false, underline::Bool=false, blink::Bool=false, reverse::Bool=false, hidden::Bool=false, color::Union{Symbol,Int}=:normal)Printxs in a color specified as a symbol or integer, optionally in bold.
Keywordcolor may take any of the values:normal,:italic,:default,:bold,:black,:blink,:blue,:cyan,:green,:hidden,:light_black,:light_blue,:light_cyan,:light_green,:light_magenta,:light_red,:light_white,:light_yellow,:magenta,:nothing,:red,:reverse,:underline,:white, or:yellow or an integer between 0 and 255 inclusive. Note that not all terminals support 256 colors.
Keywordsbold=true,italic=true,underline=true,blink=true are self-explanatory. Keywordreverse=true prints with foreground and background colors exchanged, andhidden=true should be invisible in the terminal but can still be copied. These properties can be used in any combination.
Base.sprint —Functionsprint(f::Function, args...; context=nothing, sizehint=0)Call the given function with an I/O stream and the supplied extra arguments. Everything written to this I/O stream is returned as a string.context can be anIOContext whose properties will be used, aPair specifying a property and its value, or a tuple ofPair specifying multiple properties and their values.sizehint suggests the capacity of the buffer (in bytes).
The optional keyword argumentcontext can be set to a:key=>value pair, a tuple of:key=>value pairs, or anIO orIOContext object whose attributes are used for the I/O stream passed tof. The optionalsizehint is a suggested size (in bytes) to allocate for the buffer used to write the string.
Examples
julia> sprint(show, 66.66666; context=:compact => true)"66.6667"julia> sprint(showerror, BoundsError([1], 100))"BoundsError: attempt to access 1-element Vector{Int64} at index [100]"sourceBase.showerror —Functionshowerror(io, e)Show a descriptive representation of an exception objecte. This method is used to display the exception after a call tothrow.
Examples
julia> struct MyException <: Exception msg::String endjulia> function Base.showerror(io::IO, err::MyException) print(io, "MyException: ") print(io, err.msg) endjulia> err = MyException("test exception")MyException("test exception")julia> sprint(showerror, err)"MyException: test exception"julia> throw(MyException("test exception"))ERROR: MyException: test exceptionsourceBase.dump —Functiondump(x; maxdepth=8)Show every part of the representation of a value. The depth of the output is truncated atmaxdepth.
Examples
julia> struct MyStruct x y endjulia> x = MyStruct(1, (2,3));julia> dump(x)MyStruct x: Int64 1 y: Tuple{Int64, Int64} 1: Int64 2 2: Int64 3julia> dump(x; maxdepth = 1)MyStruct x: Int64 1 y: Tuple{Int64, Int64}sourceBase.Meta.@dump —Macro@dump exprShow every part of the representation of the given expression. Equivalent todump(:(expr)).
Base.readline —Functionreadline(io::IO=stdin; keep::Bool=false)readline(filename::AbstractString; keep::Bool=false)Read a single line of text from the given I/O stream or file (defaults tostdin). When reading from a file, the text is assumed to be encoded in UTF-8. Lines in the input end with'\n' or"\r\n" or the end of an input stream. Whenkeep is false (as it is by default), these trailing newline characters are removed from the line before it is returned. Whenkeep is true, they are returned as part of the line.
Return aString. See alsocopyline to instead write in-place to another stream (which can be a preallocatedIOBuffer).
See alsoreaduntil for reading until more general delimiters.
Examples
julia> write("my_file.txt", "JuliaLang is a GitHub organization.\nIt has many members.\n");julia> readline("my_file.txt")"JuliaLang is a GitHub organization."julia> readline("my_file.txt", keep=true)"JuliaLang is a GitHub organization.\n"julia> rm("my_file.txt")julia> print("Enter your name: ")Enter your name:julia> your_name = readline()Logan"Logan"sourceBase.readuntil —Functionreaduntil(stream::IO, delim; keep::Bool = false)readuntil(filename::AbstractString, delim; keep::Bool = false)Read a string from an I/Ostream or a file, up to the given delimiter. The delimiter can be aUInt8,AbstractChar, string, or vector. Keyword argumentkeep controls whether the delimiter is included in the result. The text is assumed to be encoded in UTF-8.
Return aString ifdelim is anAbstractChar or a string or otherwise return aVector{typeof(delim)}. See alsocopyuntil to instead write in-place to another stream (which can be a preallocatedIOBuffer).
Examples
julia> write("my_file.txt", "JuliaLang is a GitHub organization.\nIt has many members.\n");julia> readuntil("my_file.txt", 'L')"Julia"julia> readuntil("my_file.txt", '.', keep = true)"JuliaLang is a GitHub organization."julia> rm("my_file.txt")sourceBase.readlines —Functionreadlines(io::IO=stdin; keep::Bool=false)readlines(filename::AbstractString; keep::Bool=false)Read all lines of an I/O stream or a file as a vector of strings. Behavior is equivalent to saving the result of readingreadline repeatedly with the same arguments and saving the resulting lines as a vector of strings. See alsoeachline to iterate over the lines without reading them all at once.
Examples
julia> write("my_file.txt", "JuliaLang is a GitHub organization.\nIt has many members.\n");julia> readlines("my_file.txt")2-element Vector{String}: "JuliaLang is a GitHub organization." "It has many members."julia> readlines("my_file.txt", keep=true)2-element Vector{String}: "JuliaLang is a GitHub organization.\n" "It has many members.\n"julia> rm("my_file.txt")sourceBase.eachline —Functioneachline(io::IO=stdin; keep::Bool=false)eachline(filename::AbstractString; keep::Bool=false)Create an iterableEachLine object that will yield each line from an I/O stream or a file. Iteration callsreadline on the stream argument repeatedly withkeep passed through, determining whether trailing end-of-line characters are retained. When called with a file name, the file is opened once at the beginning of iteration and closed at the end. If iteration is interrupted, the file will be closed when theEachLine object is garbage collected.
To iterate over each line of aString,eachline(IOBuffer(str)) can be used.
Iterators.reverse can be used on anEachLine object to read the lines in reverse order (for files, buffers, and other I/O streams supportingseek), andfirst orlast can be used to extract the initial or final lines, respectively.
Examples
julia> write("my_file.txt", "JuliaLang is a GitHub organization.\n It has many members.\n");julia> for line in eachline("my_file.txt") print(line) endJuliaLang is a GitHub organization. It has many members.julia> rm("my_file.txt");sourceBase.copyline —Functioncopyline(out::IO, io::IO=stdin; keep::Bool=false)copyline(out::IO, filename::AbstractString; keep::Bool=false)Copy a single line of text from an I/Ostream or a file to theout stream, returningout.
When reading from a file, the text is assumed to be encoded in UTF-8. Lines in the input end with'\n' or"\r\n" or the end of an input stream. Whenkeep is false (as it is by default), these trailing newline characters are removed from the line before it is returned. Whenkeep is true, they are returned as part of the line.
Similar toreadline, which returns aString; in contrast,copyline writes directly toout, without allocating a string. (This can be used, for example, to read data into a pre-allocatedIOBuffer.)
See alsocopyuntil for reading until more general delimiters.
Examples
julia> write("my_file.txt", "JuliaLang is a GitHub organization.\nIt has many members.\n");julia> String(take!(copyline(IOBuffer(), "my_file.txt")))"JuliaLang is a GitHub organization."julia> String(take!(copyline(IOBuffer(), "my_file.txt", keep=true)))"JuliaLang is a GitHub organization.\n"julia> rm("my_file.txt")sourceBase.copyuntil —Functioncopyuntil(out::IO, stream::IO, delim; keep::Bool = false)copyuntil(out::IO, filename::AbstractString, delim; keep::Bool = false)Copy a string from an I/Ostream or a file, up to the given delimiter, to theout stream, returningout. The delimiter can be aUInt8,AbstractChar, string, or vector. Keyword argumentkeep controls whether the delimiter is included in the result. The text is assumed to be encoded in UTF-8.
Similar toreaduntil, which returns aString; in contrast,copyuntil writes directly toout, without allocating a string. (This can be used, for example, to read data into a pre-allocatedIOBuffer.)
Examples
julia> write("my_file.txt", "JuliaLang is a GitHub organization.\nIt has many members.\n");julia> String(take!(copyuntil(IOBuffer(), "my_file.txt", 'L')))"Julia"julia> String(take!(copyuntil(IOBuffer(), "my_file.txt", '.', keep = true)))"JuliaLang is a GitHub organization."julia> rm("my_file.txt")sourceBase.displaysize —Functiondisplaysize([io::IO]) -> (lines, columns)Return the nominal size of the screen that may be used for rendering output to thisIO object. If no input is provided, the environment variablesLINES andCOLUMNS are read. If those are not set, a default size of(24, 80) is returned.
Examples
julia> withenv("LINES" => 30, "COLUMNS" => 100) do displaysize() end(30, 100)To get your TTY size,
julia> displaysize(stdout)(34, 147)sourceJust as text output is performed byprint and user-defined types can indicate their textual representation by overloadingshow, Julia provides a standardized mechanism for rich multimedia output (such as images, formatted text, or even audio and video), consisting of three parts:
display(x) to request the richest available multimedia display of a Julia objectx (with a plain-text fallback).show allows one to indicate arbitrary multimedia representations (keyed by standard MIME types) of user-defined types.AbstractDisplay type and pushing them onto a stack of display backends viapushdisplay.The base Julia runtime provides only plain-text display, but richer displays may be enabled by loading external modules or by using graphical Julia environments (such as the IPython-based IJulia notebook).
Base.Multimedia.AbstractDisplay —TypeAbstractDisplayAbstract supertype for rich display output devices.TextDisplay is a subtype of this.
Base.Multimedia.display —Functiondisplay(x)display(d::AbstractDisplay, x)display(mime, x)display(d::AbstractDisplay, mime, x)Displayx using the topmost applicable display in the display stack, typically using the richest supported multimedia output forx, with plain-textstdout output as a fallback. Thedisplay(d, x) variant attempts to displayx on the given displayd only, throwing aMethodError ifd cannot display objects of this type.
In general, you cannot assume thatdisplay output goes tostdout (unlikeprint(x) orshow(x)). For example,display(x) may open up a separate window with an image.display(x) means "showx in the best way you can for the current output device(s)." If you want REPL-like text output that is guaranteed to go tostdout, useshow(stdout, "text/plain", x) instead.
There are also two variants with amime argument (a MIME type string, such as"image/png"), which attempt to displayx using the requested MIME typeonly, throwing aMethodError if this type is not supported by either the display(s) or byx. With these variants, one can also supply the "raw" data in the requested MIME type by passingx::AbstractString (for MIME types with text-based storage, such as text/html or application/postscript) orx::Vector{UInt8} (for binary MIME types).
To customize how instances of a type are displayed, overloadshow rather thandisplay, as explained in the manual section oncustom pretty-printing.
Base.Multimedia.redisplay —Functionredisplay(x)redisplay(d::AbstractDisplay, x)redisplay(mime, x)redisplay(d::AbstractDisplay, mime, x)By default, theredisplay functions simply calldisplay. However, some display backends may overrideredisplay to modify an existing display ofx (if any). Usingredisplay is also a hint to the backend thatx may be redisplayed several times, and the backend may choose to defer the display until (for example) the next interactive prompt.
Base.Multimedia.displayable —Functiondisplayable(mime) -> Booldisplayable(d::AbstractDisplay, mime) -> BoolReturn a boolean value indicating whether the givenmime type (string) is displayable by any of the displays in the current display stack, or specifically by the displayd in the second variant.
Base.show —Methodshow(io::IO, mime, x)Thedisplay functions ultimately callshow in order to write an objectx as a givenmime type to a given I/O streamio (usually a memory buffer), if possible. In order to provide a rich multimedia representation of a user-defined typeT, it is only necessary to define a newshow method forT, via:show(io, ::MIME"mime", x::T) = ..., wheremime is a MIME-type string and the function body callswrite (or similar) to write that representation ofx toio. (Note that theMIME"" notation only supports literal strings; to constructMIME types in a more flexible manner useMIME{Symbol("")}.)
For example, if you define aMyImage type and know how to write it to a PNG file, you could define a functionshow(io, ::MIME"image/png", x::MyImage) = ... to allow your images to be displayed on any PNG-capableAbstractDisplay (such as IJulia). As usual, be sure toimport Base.show in order to add new methods to the built-in Julia functionshow.
Technically, theMIME"mime" macro defines a singleton type for the givenmime string, which allows us to exploit Julia's dispatch mechanisms in determining how to display objects of any given type.
The default MIME type isMIME"text/plain". There is a fallback definition fortext/plain output that callsshow with 2 arguments, so it is not always necessary to add a method for that case. If a type benefits from custom human-readable output though,show(::IO, ::MIME"text/plain", ::T) should be defined. For example, theDay type uses1 day as the output for thetext/plain MIME type, andDay(1) as the output of 2-argumentshow.
Examples
julia> struct Day n::Int endjulia> Base.show(io::IO, ::MIME"text/plain", d::Day) = print(io, d.n, " day")julia> Day(1)1 dayContainer types generally implement 3-argumentshow by callingshow(io, MIME"text/plain"(), x) for elementsx, with:compact => true set in anIOContext passed as the first argument.
Base.Multimedia.showable —Functionshowable(mime, x)Return a boolean value indicating whether or not the objectx can be written as the givenmime type.
(By default, this is determined automatically by the existence of the correspondingshow method fortypeof(x). Some types provide customshowable methods; for example, if the available MIME formats depend on thevalue ofx.)
Examples
julia> showable(MIME("text/plain"), rand(5))truejulia> showable("image/png", rand(5))falsesourceBase.repr —Methodrepr(mime, x; context=nothing)Return anAbstractString orVector{UInt8} containing the representation ofx in the requestedmime type, as written byshow(io, mime, x) (throwing aMethodError if no appropriateshow is available). AnAbstractString is returned for MIME types with textual representations (such as"text/html" or"application/postscript"), whereas binary data is returned asVector{UInt8}. (The functionistextmime(mime) returns whether or not Julia treats a givenmime type as text.)
The optional keyword argumentcontext can be set to:key=>value pair or anIO orIOContext object whose attributes are used for the I/O stream passed toshow.
As a special case, ifx is anAbstractString (for textual MIME types) or aVector{UInt8} (for binary MIME types), therepr function assumes thatx is already in the requestedmime format and simply returnsx. This special case does not apply to the"text/plain" MIME type. This is useful so that raw data can be passed todisplay(m::MIME, x).
In particular,repr("text/plain", x) is typically a "pretty-printed" version ofx designed for human consumption. See alsorepr(x) to instead return a string corresponding toshow(x) that may be closer to how the value ofx would be entered in Julia.
Examples
julia> A = [1 2; 3 4];julia> repr("text/plain", A)"2×2 Matrix{Int64}:\n 1 2\n 3 4"sourceBase.Multimedia.MIME —TypeMIMEA type representing a standard internet data format. "MIME" stands for "Multipurpose Internet Mail Extensions", since the standard was originally used to describe multimedia attachments to email messages.
AMIME object can be passed as the second argument toshow to request output in that format.
Examples
julia> show(stdout, MIME("text/plain"), "hi")"hi"sourceBase.Multimedia.@MIME_str —MacroAs mentioned above, one can also define new display backends. For example, a module that can display PNG images in a window can register this capability with Julia, so that callingdisplay(x) on types with PNG representations will automatically display the image using the module's window.
In order to define a new display backend, one should first create a subtypeD of the abstract classAbstractDisplay. Then, for each MIME type (mime string) that can be displayed onD, one should define a functiondisplay(d::D, ::MIME"mime", x) = ... that displaysx as that MIME type, usually by callingshow(io, mime, x) orrepr(io, mime, x). AMethodError should be thrown ifx cannot be displayed as that MIME type; this is automatic if one callsshow orrepr. Finally, one should define a functiondisplay(d::D, x) that queriesshowable(mime, x) for themime types supported byD and displays the "best" one; aMethodError should be thrown if no supported MIME types are found forx. Similarly, some subtypes may wish to overrideredisplay(d::D, ...). (Again, one shouldimport Base.display to add new methods todisplay.) The return values of these functions are up to the implementation (since in some cases it may be useful to return a display "handle" of some type). The display functions forD can then be called directly, but they can also be invoked automatically fromdisplay(x) simply by pushing a new display onto the display-backend stack with:
Base.Multimedia.pushdisplay —Functionpushdisplay(d::AbstractDisplay)Pushes a new displayd on top of the global display-backend stack. Callingdisplay(x) ordisplay(mime, x) will displayx on the topmost compatible backend in the stack (i.e., the topmost backend that does not throw aMethodError).
Base.Multimedia.popdisplay —Functionpopdisplay()popdisplay(d::AbstractDisplay)Pop the topmost backend off of the display-backend stack, or the topmost copy ofd in the second variant.
Base.Multimedia.TextDisplay —TypeTextDisplay(io::IO)Return aTextDisplay <: AbstractDisplay, which displays any object as the text/plain MIME type (by default), writing the text representation to the given I/O stream. (This is how objects are printed in the Julia REPL.)
Base.Multimedia.istextmime —Functionistextmime(m::MIME)Determine whether a MIME type is text data. MIME types are assumed to be binary data except for a set of types known to be text data (possibly Unicode).
Examples
julia> istextmime(MIME("text/plain"))truejulia> istextmime(MIME("image/png"))falsesourceBase.bytesavailable —Functionbytesavailable(io)Return the number of bytes available for reading before a read from this stream or buffer will block.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization");julia> bytesavailable(io)34sourceBase.ENDIAN_BOM —ConstantENDIAN_BOMThe 32-bit byte-order-mark indicates the native byte order of the host machine. Little-endian machines will contain the value0x04030201. Big-endian machines will contain the value0x01020304.
Settings
This document was generated withDocumenter.jl version 1.16.0 onThursday 20 November 2025. Using Julia version 1.12.2.