I/O and Network
Common I/O
#
Base.read
— Method
read(filename::AbstractString)
Reads the entire contents of the file as Vector{UInt8}
.
read(filename::AbstractString, String)
Reads the entire contents of the file as a string.
read(filename::AbstractString, args...)
Opens the file and reads its contents. 'args` is passed to read
: this is equivalent to open(io->read(io, args...), filename)
.
#
Base.write
— Method
write(filename::AbstractString, content)
Writes the canonical binary representation of `content' to a file that will be created if it does not already exist, or overwritten otherwise.
Returns the number of bytes written to the file.
#
Base.open
— Function
open(f::Function, args...; kwargs...)
Applies the function f
to the result open(args...; kwargs...)
and closes the handle of the resulting file upon completion.
Examples
julia> write("myfile.txt", "Hello world!");
julia> open(io->read(io, String), "myfile.txt")
"Hello world!"
julia> rm("myfile.txt")
open(filename::AbstractString; lock = true, keywords...) -> IOStream
Opens the file in the mode specified by five logical named arguments:
Named argument | Description | Default value |
---|---|---|
|
open for reading |
|
|
open for recording |
|
|
create if it does not exist |
|
|
crop to zero size |
|
|
perform the search to the end |
|
By default, if no keywords are transmitted, the files will be read-only. The stream returns to access the open file.
The named lock
argument determines whether operations will be blocked for secure multithreaded access.
Compatibility: Julia 1.5
The |
open(filename::AbstractString, [mode::AbstractString]; lock = true) -> IOStream
An alternative opening syntax that uses a mode descriptor based on string operations instead of five logical arguments. The mode
values correspond to the values from fopen(3)
or Perl open
and are equivalent to configuring the following logical groups:
Mode | Description | Named arguments |
---|---|---|
|
reading |
no |
|
reading, creating, cropping |
|
|
reading, creating, joining |
|
|
reading, writing |
|
|
reading, writing, creating, cropping |
|
|
reading, writing, creating, joining |
|
The named lock
argument determines whether operations will be blocked for secure multithreaded 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")
28
julia> close(io)
julia> rm("myfile.txt")
Compatibility: Julia 1.5
The |
open(fd::OS_HANDLE) -> IO
Encapsulates the raw file descriptor in a Julia-enabled I/O type and takes ownership of the file device descriptor. Calls open(Libc.dup(fd))
to prevent transfer of ownership of the source descriptor.
Do not call this function for a handle that is already owned by another part of the system. |
open(command, mode::AbstractString, stdio=devnull)
Executes the command
in asynchronous mode. Similar to open(command, stdio; read, write)
, except that the read and write flags are set using the mode string instead of named arguments. The following mode lines are possible:
Mode | Description | Named arguments |
---|---|---|
|
reading |
no |
|
record |
|
|
reading, writing |
|
|
reading, writing |
|
open(command, stdio=devnull; write::Bool = false, read::Bool = !write)
Starts executing command
in asynchronous mode and returns the process::IO
object. If read
is set to true, the process data being read is received from the standard output of the process and the standard input stream of the process is additionally set to stdio
. If write
is set to true, the data being written is sent to the standard input of the process and the standard output stream of the process is additionally set to stdio
. The standard error stream of the process is connected to the current global `stderr'.
open(f::Function, command, args...; kwargs...)
Similarly, open(command, args...; kwargs...)
, but causes f(stream)
for the resulting process stream, and then closes the input stream and waits for the process to finish. Returns the value returned by f
if successful. An error occurs if the process has failed or is trying to print data in stdout.
#
Base.IOBuffer
— Type
IOBuffer([data::AbstractVector{UInt8}]; keywords...) -> IOBuffer
Creates an I/O stream in memory that can additionally perform operations on an existing array.
Optional named arguments may be required.:
-
read
,write
, `append': restricts buffer operations; for more information, see `open'. -
`truncate': truncates the buffer size to zero length.
-
`maxsize': Sets the size beyond which the buffer cannot be increased.
-
sizehint
: suggests buffer capacity (data
should implementsizehint!(data, size)
).
If the data
argument is omitted, the buffer will be available for reading and writing by default.
Examples
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
56
julia> 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 writeable
julia> 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.")
34
julia> String(take!(io))
"JuliaLang is a GitHub organization"
julia> length(read(IOBuffer(b"data", read=true, truncate=false)))
4
julia> length(read(IOBuffer(b"data", read=true, truncate=true)))
0
IOBuffer(string::String)
Creates an IOBuffer
with the read-only property for the data that is the base for this row.
Examples
julia> io = IOBuffer("Haho");
julia> String(take!(io))
"Haho"
julia> String(take!(io))
"Haho"
#
Base.take!
— Method
take!(b::IOBuffer)
Gets the contents of the IOBuffer
as an array. After that, the `IOBuffer' is reset to its original state.
Examples
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
56
julia> String(take!(io))
"JuliaLang is a GitHub organization. It has many members."
#
Base.Pipe
— Type
Pipe()
Creates an uninitialized Pipe object (pipeline), in particular for I/O operations between multiple processes.
The corresponding end of the pipeline will be automatically initialized if the object is used when the process is spawned. This can be useful for easily obtaining references in process pipelines, for example:
julia> err = Pipe() # После этого `err` будет инициализирован и можно будет прочитать поток stderr # `foo` из конвейера `err` или передать `err` в другие конвейеры. julia> run(pipeline(pipeline(`foo`, stderr=err), `cat`), wait=false) # Теперь уничтожим половину конвейера, предназначенную для записи, чтобы половина, предназначенная для чтения, получила EOF julia> closewrite(err) julia> read(err, String) "stderr messages"
See also the description Base.link_pipe!
.
#
Base.link_pipe!
— Function
link_pipe!(pipe; reader_supports_async=false, writer_supports_async=false)
Initializes the pipe
and binds the in
endpoint to the out
endpoint. The named arguments reader_supports_async
and writer_supports_async
correspond to OVERLAPPED
on Windows and O_NONBLOCK
on POSIX systems. They must have the value true
unless they are used by an external program (for example, by outputting a command executed using run
).
#
Base.fdio
— Function
fdio([name::AbstractString, ]fd::Integer[, own::Bool=false]) -> IOStream
Creates an object 'IOStream` based on an integer file descriptor. If own
has the value true', then when closing this object, the base descriptor is also closed. By default, the `IOStream
is closed when garbage collection is performed. name
allows you to associate a descriptor with a named file.
#
Base.flush
— Function
flush(stream)
Captures all previously buffered write operations in a given stream.
#
Base.closewrite
— Function
closewrite(stream)
Stops recording half of the full-duplex I/O stream. First, it runs flush
. Notifies the other party that data is no longer being written to the base file. This operation may not be supported for some I/O types.
If implemented, closewrite
causes subsequent calls to read
or eof
, which would have blocked, to instead return EOF or true, respectively. If the thread is already closed, it is idempotent.
Examples
julia> io = Base.BufferStream(); # в этом случае блокировка никогда не выполняется, поэтому операции чтения и записи доступны для той же задачи
julia> write(io, "request");
julia> # при вызове здесь `read(io)` применяется постоянная блокировка
julia> closewrite(io);
julia> read(io, String)
"request"
#
Base.write
— Function
write(io::IO, x)
Writes the canonical binary representation of a value to a specified input/output stream or file. Returns the number of bytes written to the stream. See also the function description print
, which writes a text representation (in an encoding that depends on io
).
The byte order in the recorded value depends on the byte order in the host system. In the process of writing or reading, it performs a conversion to or from a fixed byte order (for example, using htol
and ltoh
) so that the results are consistent across platforms.
You can write multiple values with a single write
call, meaning the following values are equivalent:
write(io, x, y...) write(io, x) + write(io, y...)
Examples
Consistent serialization:
julia> fname = tempname(); # произвольное временное имя файла
julia> open(fname,"w") do f
# Убедиться в том, что выполняется запись 64-разрядного целочисленного значения в формате прямого порядка следования байтов
write(f,htol(Int64(42)))
end
8
julia> open(fname,"r") do f
# Perform the reverse conversion to the basic byte order and the basic integer type
Int(ltoh(read(f,Int64)))
end
42
Combining calls of write operations:
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
56
julia> String(take!(io))
"JuliaLang is a GitHub organization. It has many members."
julia> write(io, "Sometimes those members") + write(io, " write documentation.")
44
julia> String(take!(io))
"Sometimes those members write documentation."
User-defined core data types without write
methods can be written and then encapsulated in Ref
:
julia> struct MyStruct; x::Float64; end
julia> 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)))
8
julia> seekstart(io); read!(io, Ref(MyStruct(NaN)))
Base.RefValue{MyStruct}(MyStruct(42.0))
#
Base.read
— Function
read(io::IO, T)
Reads a single value of type T
from io
in the canonical binary representation.
read(io::IO, String)
Reads io
completely as a String' (see also `readchomp
).
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"
read(filename::AbstractString)
Reads the entire contents of the file as Vector{UInt8}
.
read(filename::AbstractString, String)
Reads the entire contents of the file as a string.
read(filename::AbstractString, args...)
Opens the file and reads its contents. 'args` is passed to read
: this is equivalent to open(io->read(io, args...), filename)
.
read(s::IO, nb=typemax(Int))
Reads no more than nb
bytes from s
, returning Vector{UInt8}
with the bytes read.
read(s::IOStream, nb::Integer; all=true)
Reads no more than nb
bytes from s
, returning Vector{UInt8}
with the bytes read.
If all
is set to true
(by default), this function will permanently block when trying to read all the requested bytes until an error occurs or the end of the file is reached. If all
is set to false
, no more than one read
call is executed, and the amount of data returned will depend on the device. Note that the all
parameter may not be supported for some stream types.
read(command::Cmd)
Executes the command
and returns the resulting output as an array of bytes.
read(command::Cmd, String)
Executes the command
and returns the resulting output as a `String'.
#
Base.read!
— Function
read!(stream::IO, array::AbstractArray)
read!(filename::AbstractString, array::AbstractArray)
Reads binary data from an I/O stream or file by filling in an `array'.
#
Base.readbytes!
— Function
readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b))
Reads no more than nb
bytes from stream
to b
, returning the number of bytes read. The size of b
increases if necessary (that is, if nb
is greater than length(b)
and a sufficient number of bytes have been counted), but it never decreases.
readbytes!(stream::IOStream, b::AbstractVector{UInt8}, nb=length(b); all::Bool=true)
Reads no more than nb
bytes from stream
to b
, returning the number of bytes read. The size of b
increases if necessary (that is, if nb
is greater than length(b)
and a sufficient number of bytes have been counted), but it never decreases.
If all
is set to true
(by default), this function will permanently block when trying to read all the requested bytes until an error occurs or the end of the file is reached. If all
is set to false
, no more than one read
call is executed, and the amount of data returned will depend on the device. Note that the all
parameter may not be supported for some stream types.
#
Base.unsafe_read
— Function
unsafe_read(io::IO, ref, nbytes::UInt)
Copies nbytes
from the object of the IO
stream to ref
(converted to a pointer).
In the subtypes T<:IO
, it is recommended to redefine the following method signature to provide more efficient implementations: unsafe(s::T, p::Ptr{UInt8}, n::UInt)
.
#
Base.unsafe_write
— Function
unsafe_write(io::IO, ref, nbytes::UInt)
Copies nbytes
from ref' (converted to a pointer) to the `IO
object.
In the subtypes T<:IO
, it is recommended to redefine the following method signature to provide more efficient implementations: unsafe(s::T, p::Ptr{UInt8}, n::UInt)
.
#
Base.readeach
— Function
readeach(io::IO, T)
Returns an iterable object that outputs read(io, T)
.
Compatibility: Julia 1.6
Readeach requires a Julia version of 1.6 or higher. |
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)
end
JuliaLang is a GitHub organization.
#
Base.peek
— Function
peek(stream[, T=UInt8])
Reads and returns a value of type T
from the stream without moving forward from the current position in the stream. See also the description startswith(stream, char_or_string)
.
Examples
julia> b = IOBuffer("julia");
julia> peek(b)
0x6a
julia> position(b)
0
julia> peek(b, Char)
'j': ASCII/Unicode U+006A (category Ll: Letter, lowercase)
Compatibility: Julia 1.5
A method that accepts a type requires a Julia version of 1.5 or higher. |
#
Base.position
— Function
position(l::Lexer)
Returns the current position.
position(s)
Gets the current position in the stream.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> seek(io, 5);
julia> position(io)
5
julia> skip(io, 10);
julia> position(io)
15
julia> seekend(io);
julia> position(io)
35
#
Base.seek
— Function
seek(s, pos)
Performs a search through the stream until the specified position is reached.
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)
#
Base.seekstart
— Function
seekstart(s)
Performs a search through the stream until it reaches 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)
#
Base.skip
— Function
skip(s, offset)
Performs a flow search relative to the current position.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> seek(io, 5);
julia> skip(io, 10);
julia> read(io, Char)
'G': ASCII/Unicode U+0047 (category Lu: Letter, uppercase)
#
Base.eof
— Function
eof(stream) -> Bool
Checks whether the I/O stream is at the end of the file. If the stream has not been exhausted yet, this function blocks, waiting for additional data (if necessary), and then returns false'. Therefore, it is always safe to read one byte at a time after `eof
returns false'. 'eof
will return `false' as long as buffered data is available, even if the remote end of the connection is closed.
Examples
julia> b = IOBuffer("my buffer");
julia> eof(b)
false
julia> seekend(b);
julia> eof(b)
true
#
Base.isreadonly
— Function
isreadonly(io) -> Bool
Determines whether the stream has the "read-only" property.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization");
julia> isreadonly(io)
true
julia> io = IOBuffer();
julia> isreadonly(io)
false
#
Base.iswritable
— Function
iswritable(path::String)
Returns the value true
if, according to the access permissions for this path
object, the current user can write to it.
This permission may change before the user calls |
Currently, this function incorrectly polls the Windows file system ACL, so it may return incorrect results. |
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
See also the description ispath
, isexecutable
and isreadable
.
iswritable(io) -> Bool
Returns false
if writing to the specified I/O object is not supported.
Examples
julia> open("myfile.txt", "w") do io
print(io, "Hello world!");
iswritable(io)
end
true
julia> open("myfile.txt", "r") do io
iswritable(io)
end
false
julia> rm("myfile.txt")
#
Base.isreadable
— Function
isreadable(path::String)
Returns the value true
if, according to the access permissions for this path
object, the current user can read from it.
This permission may change before the user calls |
Currently, this function incorrectly polls the Windows file system ACL, so it may return incorrect results. |
Compatibility: Julia 1.11
This feature requires a version of Julia not lower than 1.11. |
See also the description ispath
, isexecutable
and iswritable
.
isreadable(io) -> Bool
Returns false
if reading from the specified I/O object is not supported.
Examples
julia> open("myfile.txt", "w") do io
print(io, "Hello world!");
isreadable(io)
end
false
julia> open("myfile.txt", "r") do io
isreadable(io)
end
true
julia> rm("myfile.txt")
#
Base.isexecutable
— Function
isexecutable(path::String)
Returns true
if the specified path
has executable file permissions.
This permission may change before the user executes the |
Prior to Julia 1.6, the Windows file system ACL was queried incorrectly, so the value |
See also the description ispath
, isreadable
and iswritable
.
#
Base.isopen
— Function
isopen(object) -> Bool
Determines whether the object (thread or timer) is already closed. After the object is closed, it will not be able to create new events. However, considering that a closed stream can still contain data for reading in the buffer, you should use 'eof` to check the readability of the data. Use the FileWatching package to receive notifications if writing to or reading from a stream is supported.
Examples
julia> io = open("my_file.txt", "w+");
julia> isopen(io)
true
julia> close(io)
julia> isopen(io)
false
#
Base.fd
— Function
fd(stream)
Returns the file descriptor that reserves the stream or file. Note that this function is applicable only to synchronous File
and IOStream
, but not to asynchronous streams.
#
Base.redirect_stdio
— Function
redirect_stdio(;stdin=stdin, stderr=stderr, stdout=stdout)
Redirects a subset of the streams stdin
, stderr
, stdout'. Each argument must be `IOStream', `TTY
, Pipe
, socket, or `devnull'.
Compatibility: Julia 1.7
redirect_stdio requires a version of Julia at least 1.7. |
redirect_stdio(f; stdin=nothing, stderr=nothing, stdout=nothing)
Redirects a subset of the streams stdin
, stderr
, stdout', calls `f()
and restores each of the threads.
Possible values for each stream:
-
`nothing', indicating that the stream should not be redirected.
-
path::AbstractString' redirecting the stream to a file in `path
. -
io
andIOStream', `TTY
,Pipe
, socket, or `devnull'.
Examples
julia> redirect_stdio(stdout="stdout.txt", stderr="stderr.txt") do
print("hello stdout")
print(stderr, "hello stderr")
end
julia> read("stdout.txt", String)
"hello stdout"
julia> read("stderr.txt", String)
"hello stderr"
Borderline cases
You can pass the same argument to stdout
and stderr
:
julia> redirect_stdio(stdout="log.txt", stderr="log.txt", stdin=devnull) do
...
end
However, you cannot transfer two separate 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) # не поддерживается
In addition, the stdin
argument may not be the same descriptor as stdout
or `stderr'.
julia> io = open(...)
julia> redirect_stdio(f, stdout=io, stdin=io) # не поддерживается
Compatibility: Julia 1.7
redirect_stdio requires a version of Julia at least 1.7. |
#
Base.redirect_stdout
— Function
redirect_stdout([stream]) -> stream
Creates a transmission channel to which all output is redirected. stdout
level C and Julia. Returns a stream representing the ends of the transmission channel. Data written to 'stdout`, cannot be read from the end of the rd
transmission channel.
|
See also the description redirect_stdio
.
#
Base.redirect_stderr
— Function
redirect_stderr([stream]) -> stream
Similarly redirect_stdout
, but for stderr
.
|
See also the description redirect_stdio
.
#
Base.redirect_stdin
— Function
redirect_stdin([stream]) -> stream
Similarly redirect_stdout
, but for stdin
. Note that the flow direction is reversed.
|
See also the description redirect_stdio
.
#
Base.readchomp
— Function
readchomp(x)
Reads the x
completely as a string and deletes one newline character at the end (if any). Equivalent to chomp(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");
#
Base.truncate
— Function
truncate(file, n)
Modifies the size of the file or buffer passed in the first argument by exactly n
bytes, filling previously unallocated space with "\0" characters if the file or buffer size increases.
Examples
julia> io = IOBuffer();
julia> write(io, "JuliaLang is a GitHub organization.")
35
julia> 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"
#
Base.skipchars
— Function
skipchars(predicate, io::IO; linecomment=nothing)
Moves the io
stream forward so that the next character to be read is the first of the remaining ones, for which 'predict' returns false'. If the named argument `linecomment
is set, all characters from this character up to the beginning of the next line will be 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"
#
Base.countlines
— Function
countlines(io::IO; eol::AbstractChar = '\n')
countlines(filename::AbstractString; eol::AbstractChar = '\n')
Reads the io
up to the end of the stream or file and counts the number of lines. To specify a file, pass the file name as the first argument. End-of-line markers other than , are supported by passing them as a second argument. The last non-empty line in io
is taken into account, even if it does not end with an end-of-line marker, matching the length of the value returned. eachline
and readlines
.
To count the String
lines, you can use `countlines(IOBuffer(str))'.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization.\n");
julia> countlines(io)
1
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> countlines(io)
1
julia> eof(io) # при подсчете строк перемещается указатель файла
true
julia> io = IOBuffer("JuliaLang is a GitHub organization.");
julia> countlines(io, eol = '.')
1
julia> write("my_file.txt", "JuliaLang is a GitHub organization.\n")
36
julia> countlines("my_file.txt")
1
julia> countlines("my_file.txt", eol = 'n')
4
julia> rm("my_file.txt")
#
Base.PipeBuffer
— Function
PipeBuffer(data::AbstractVector{UInt8}=UInt8[]; maxsize::Integer = typemax(Int))
An object 'IOBuffer', which allows reading and writing by joining. Search and cropping are not supported. Cm. 'IOBuffer', which describes the available constructors. If the data
argument is specified, a `PipeBuffer' is created that performs operations on the data vector, additionally specifying the size beyond which the base array cannot be increased.
#
Base.readavailable
— Function
readavailable(stream)
Reads the available buffered data from the stream. The actual I/O is performed only if the data has not been buffered yet. The result is a Vector{UInt8}
.
The amount of data returned will depend on the implementation; for example, it may depend on the internal buffer size selection. Other functions should usually be used instead, such as |
#
Base.IOContext
— Type
IOContext
The 'IOContext` provides a mechanism for passing output configuration parameters between methods show
.
In other words, it is an immutable dictionary, which is a subclass of IO'. It supports standard dictionary operations such as 'getindex
, and can also be used as an I/O stream.
#
Base.IOContext
— Method
IOContext(io::IO, KV::Pair...)
Creates an IOContext
in which this stream is encapsulated with the addition of the specified pairs key=>value
to the properties of this stream (note that io
can be an `IOContext').
-
use
(key => value) in io
to check if this particular combination is included in the property set.; -
use
get(io, key, default)
to get the latest value for a specific key.
The following properties are most commonly used:
-
:compact
: A boolean value indicating that values should be output more compactly, for example, that numbers should be output using fewer digits. It is configured when displaying array elements. The output:compact
should not contain line breaks. -
:limit
: A boolean value indicating that containers should be trimmed, for example, displaying…
instead of most elements. -
:displaysize
: Tuple tuple{Int,Int}`, which specifies the size in rows and columns to be used for text output. It can be used to redefine the display size for called functions, but thedisplaysize
function should be used to get the screen size. -
:typeinfo
:Type', which characterizes the information already displayed related to the type of the displayed object. This is particularly useful when displaying a collection of objects of the same type, avoiding redundant type information (for example, `[Float16(0)]
can be displayed as Float16[0.0] rather than as Float16[Float16(0.0)]: when displaying array elements for the:typeinfo
property, the value is set to `Float16'). -
:color
: A boolean value indicating whether ANSI color codes and alphabet change codes are supported, as well as whether they are available. By default, this is determined by whetherio
is a compatible terminal, as well as by any command-line flag--color
when runningjulia
.
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.12341234
julia> print(IOContext(stdout, :compact => true), 1.12341234)
1.12341
julia> function f(io::IO)
if get(io, :short, false)
print(io, "short")
else
print(io, "loooooong")
end
end
f (generic function with 1 method)
julia> f(stdout)
loooooong
julia> f(IOContext(stdout, :short => true))
short
#
Base.IOContext
— Method
IOContext(io::IO, context::IOContext)
Creates an IOContext' that encapsulates the alternative `IO
, but inherits the properties of the context
.
Text input/output
#
Base.show
— Method
show([io::IO = stdout], x)
Writes the text representation of the value x
to the output stream io'. The new types of `T
should overload show(io::IO, x::T)
. The representation used by show
generally includes Julia formatting and type information, and should be Julia code parsable (if possible).
repr
returns the output of `show' as a string.
For more detailed, human-readable text output for objects of type T
, additionally define show(io::IO, ::MIME"text/plain", ::T)
. It is recommended to check the :compact
key in such methods. 'IOContext` (often checked as get(io, :compact, false)::Bool
) of the io
stream, because some containers display elements by calling this method with :compact => true
.
See also the function description print
, which records undecorated representations.
Examples
julia> show("Hello World!")
"Hello World!"
julia> print("Hello World!")
Hello World!
#
Base.summary
— Function
summary(io::IO, x)
str = summary(x)
Outputs to the io
stream or returns the string str
with a brief description of the value. By default, it returns string(typeof(x))`for example `Int64
.
For arrays, a string with information about size and type is returned, for example, 10-element Array{Int64,1}
.
Examples
julia> summary(1)
"Int64"
julia> summary(zeros(2))
"2-element Vector{Float64}"
#
Base.print
— Function
print([io::IO], xs...)
Writes the canonical (undecorated) text representation to io
(or to the default output stream 'stdout`, if io
is not specified). The representation used by print
contains minimal formatting and tries to exclude details specific to Julia.
print
returns to the show
call, so most types should just define show'. Define `print
if your type contains a separate "regular" representation. For example, show
displays strings with quotes, and print
- without quotes.
See also the description println
, string
and printstyled
.
Examples
julia> print("Hello World!")
Hello World!
julia> io = IOBuffer();
julia> print(io, "Hello", ' ', :World!)
julia> String(take!(io))
"Hello World!"
#
Base.println
— Function
println([io::IO], xs...)
Outputs xs' (using `print
) in io
followed by a newline character. If the io
argument is not specified, it outputs to the default output stream. stdout
.
See also the function description printstyled
, which adds colors, etc.
Examples
julia> println("Hello, world")
Hello, world
julia> io = IOBuffer();
julia> println(io, "Hello", ',', " world.")
julia> String(take!(io))
"Hello, world.\n"
#
Base.printstyled
— Function
printstyled([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)
Outputs xs
in the color specified as a character or an integer (bold is possible).
The named argument color
can take the following 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
, :yellow
or an integer in the range from 0 to 255 inclusive. Please note that not all terminals support 256 colors.
The named arguments bold=true
, italic=true
, underline=true
, and blink=true
are self-explanatory. The named argument reverse=true
performs output with foreground and background colors replacement, and with hidden=true
the output should be invisible in the terminal, but still available for copying. These properties can be used in any combination.
Not all terminals support italics output. Some terminals interpret italics as addressing or flashing. |
Compatibility: Julia 1.7
Named arguments, with the exception of |
Compatibility: Julia 1.10
Italics output support was added in Julia 1.10. |
#
Base.sprint
— Function
sprint(f::Function, args...; context=nothing, sizehint=0)
Calls this function with an I/O stream and additional arguments provided. All data written to this I/O stream is returned as a string. The context
can be an object 'IOContext', whose properties will be used, by a Pair
object that specifies a property and its value, or by a tuple of Pair
objects that specify several properties and their values. The sizehint
specifies the preferred buffer capacity (in bytes).
The optional named argument context
can be assigned the pair :key=>value
, a tuple of pairs :key=>value
or an object IO
or 'IOContext`, the attributes of which are used for the I/O stream passed to f'. The optional `sizehint
argument specifies the preferred size (in bytes) that is allocated for the buffer used to write the string.
Compatibility: Julia 1.7
To pass a tuple in the named |
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]"
#
Base.showerror
— Function
showerror(io, e)
Displays a descriptive representation of the exception object e'. This method is used to display the exception after the call. `throw
.
Examples
julia> struct MyException <: Exception
msg::String
end
julia> function Base.showerror(io::IO, err::MyException)
print(io, "MyException: ")
print(io, err.msg)
end
julia> err = MyException("test exception")
MyException("test exception")
julia> sprint(showerror, err)
"MyException: test exception"
julia> throw(MyException("test exception"))
ERROR: MyException: test exception
#
Base.dump
— Function
dump(x; maxdepth=8)
Displays all parts of the value representation. The output depth is truncated by maxdepth
.
Examples
julia> struct MyStruct
x
y
end
julia> x = MyStruct(1, (2,3));
julia> dump(x)
MyStruct
x: Int64 1
y: Tuple{Int64, Int64}
1: Int64 2
2: Int64 3
julia> dump(x; maxdepth = 1)
MyStruct
x: Int64 1
y: Tuple{Int64, Int64}
#
Base.Meta.@dump
— Macro
@dump expr
Displays all parts of the representation of a given expression. Equivalent to dump(:(expr))
.
#
Base.readline
— Function
readline(io::IO=stdin; keep::Bool=false)
readline(filename::AbstractString; keep::Bool=false)
Reads one line of text from a given input/output stream or file (default is stdin
). When reading from a file, it is assumed that UTF-8 encoding is used for the text. Lines at the input end with either "\r\n"
or at the end of the input stream. If 'keep` is set to false (by default), these trailing newlines are removed from the string before it is returned. If keep
is set to true, they are returned as part of the string.
Returns a String'. See also the function description `copyline
, which writes to another stream (which may be pre-allocated `IOBuffer') is in place.
Also, see the function description. readuntil
for reading up to 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"
#
Base.readuntil
— Function
readuntil(stream::IO, delim; keep::Bool = false)
readuntil(filename::AbstractString, delim; keep::Bool = false)
Reads a string from an I/O stream or file up to a specified separator. The separator can be UInt8
, AbstractChar', string or vector. The named `keep
argument determines whether a separator is included in the result. It is assumed that UTF-8 encoding is used for the text.
Returns String
if delim
is an AbstractChar
or string, otherwise it returns Vector{typeof(delim)}
. See also the function description copyuntil
, which writes to another stream (which may be pre-allocated `IOBuffer') is in place.
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")
#
Base.readlines
— Function
readlines(io::IO=stdin; keep::Bool=false)
readlines(filename::AbstractString; keep::Bool=false)
Reads all lines in an I/O stream or file as a vector of string values. The behavior is similar to saving the result of a read multiple times. readline
with the same arguments and saving the resulting strings as a vector of string values. See also function description 'eachline`, which iterates through 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")
#
Base.eachline
— Function
eachline(io::IO=stdin; keep::Bool=false)
eachline(filename::AbstractString; keep::Bool=false)
Creates an iterable EachLine
object that outputs each line from an I/O stream or file. During iteration, it is repeatedly called readline
for the stream argument with the keep
argument being passed, which determines whether the final characters of the end of the line are saved. When called with a string name, the file opens once at the beginning of the iteration and closes after its completion. If the iteration is interrupted, the file will be closed when the garbage collector deletes the EachLine
object.
To iterate through each string in String
, you can use `eachline(IOBuffer(str))'.
Iterators.reverse
can be used for the EachLine
object to read lines in reverse order (for files, buffers, and other I/O streams that support seek
), and you can also use first
or last
to extract the start or end 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)
end
JuliaLang is a GitHub organization. It has many members.
julia> rm("my_file.txt");
Compatibility: Julia 1.8
In Julia 1.8, you must use |
#
Base.copyline
— Function
copyline(out::IO, io::IO=stdin; keep::Bool=false)
copyline(out::IO, filename::AbstractString; keep::Bool=false)
Copies one line of text from an I/O stream or file to an out stream, returning 'out'.
When reading from a file, it is assumed that UTF-8 encoding is used for the text. Lines at the input end with either "\r\n"
or at the end of the input stream. If 'keep` is set to false (by default), these trailing newlines are removed from the string before it is returned. If keep
is set to true, they are returned as part of the string.
It acts similarly to the function readline
, which returns String'; however, `copyline
writes directly to out
without allocating memory for the string. (This can be used, for example, to read data into a pre-allocated IOBuffer
.)
Also, see the function description. copyuntil
for reading up to more common 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")
#
Base.copyuntil
— Function
copyuntil(out::IO, stream::IO, delim; keep::Bool = false)
copyuntil(out::IO, filename::AbstractString, delim; keep::Bool = false)
Copies a string from the I/O stream stream
or a file up to the specified separator to the out
stream, returning out'. The separator can be `UInt8
, AbstractChar', string or vector. The named `keep
argument determines whether a separator is included in the result. It is assumed that UTF-8 encoding is used for the text.
It acts similarly to the function readuntil
, which returns String'; however, `copyuntil
writes directly to out
without allocating memory for the string. (This can be used, for example, to read data into a pre-allocated IOBuffer
.)
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")
#
Base.displaysize
— Function
displaysize([io::IO]) -> (lines, columns)
Returns the nominal screen size that can be used to visualize the output to the IO
object. If no input data is provided, the environment variables LINES
and COLUMNS' are read. If these variables are not set, the default size `(24, 80)
is returned.
Examples
julia> withenv("LINES" => 30, "COLUMNS" => 100) do
displaysize()
end
(30, 100)
To get the TTY size,
julia> displaysize(stdout)
(34, 147)
Multimedia I/O
Just like text output is done using print
, and custom types can specify their text representation by overloading show
, Julia provides a standardized mechanism for displaying a variety of multimedia data (such as images, formatted text, or even audio and video), consisting of three parts.
-
Function
display(x)
to request the most extensive available multimedia display of the Juliax
object (with a backup in plain text). -
Overload
show
allows you to specify arbitrary multimedia representations (with reference to standard MIME types) of user-defined types. -
Multimedia-enabled display backends can be registered by subclassing the universal type.
AbstractDisplay
and placing them in the display backend stack usingpushdisplay
.
The basic Julia runtime provides only the display of plain text, but for more extensive display capabilities, you can load external modules or use Julia graphical environments (for example, the IPython-based IJulia notebook).
#
Base.Multimedia.AbstractDisplay
— Type
AbstractDisplay
An abstract supertype for devices with formatted output. TextDisplay
is its subtype.
#
Base.Multimedia.display
— Function
display(x)
display(d::AbstractDisplay, x)
display(mime, x)
display(d::AbstractDisplay, mime, x)
Displays x
using the topmost applicable display in the display stack, typically using the fullest possible supported multimedia output for x
, with plain text output 'stdout` as a backup option. The display(d, x)
option tries to display x
only on this d
display by issuing MethodError
, if d
does not support the display of objects of this type.
In general, it should not be assumed that the output of display
goes to stdout
(unlike print(x)
or show(x)
). For example, display(x)
can open a separate window with an image. display(x)
means "display x
with maximum quality for current output devices". If you need a text output of the REPL type, which is guaranteed to go to stdout
, you should use instead show(stdout, "text/plain", x)
.
In addition, there are two options with the mime
argument (a MIME type string, for example "image/png"
) that attempt to display x
only using the requested MIME type, issuing a MethodError
if this type is not supported by displays or x
. Using these options, you can also provide the "raw" data of the requested MIME type by passing x::AbstractString' (for MIME types with text storage such as text/html or application/postscript) or `+x::Vector{UInt8}+
(for binary MIME types).
To configure the display of type instances, overload show
instead of display
as described in the manual section Customizable structural printout.
#
Base.Multimedia.redisplay
— Function
redisplay(x)
redisplay(d::AbstractDisplay, x)
redisplay(mime, x)
redisplay(d::AbstractDisplay, mime, x)
By default, the redisplay
functions simply call display
. However, some display backends may override redisplay
to change the existing x
display (if any). Using redisplay
also tells the backend that `x' can be displayed multiple times and the backend can delay the display until (for example) The following interactive command prompt will not be displayed.
#
Base.Multimedia.displayable
— Function
displayable(mime) -> Bool
displayable(d::AbstractDisplay, mime) -> Bool
Returns a boolean value indicating whether the display of this type of mime
(string) is supported by any display on the current stack or, in particular, the d
display in the second variant.
#
Base.show
— Method
show(io::IO, mime, x)
Functions display
is eventually called show' in order, if possible, to write an object `x
as a given type of mime
to a given io input/output stream (usually a memory buffer). To provide an extended multimedia representation of a user-defined type T
, you simply need to define a new show
method for T
using show(io, ::MIME"mime", x::T) = ...
where mime
is a MIME type string, and the function is called in the body of the function write
(or similar) to write this representation of x
to io'. (Note that the 'MIME' notation supports only literal strings; for more flexible construction of `MIME
types, use MIME{Symbol("")}
.)
For example, if the type myImage
is defined and it is known how it is written to the PNG file, you can define the function show(io, ::MIME"image/png", x::myImage) = ...
to allow the display of images in AbstractDisplay
with PNG support (for example, IJulia). As usual, you need to use import Base.show
to add new methods to the built-in Julia show
function.
Strictly speaking, the macro MIME"mime"
defines a single type for a given string mime
, allowing you to use Julia’s dispatching mechanisms when determining how objects of any given type are displayed.
The default MIME type is MIME "text/plain"
. There is a backup definition for the output of text/plain
, which calls show
with two arguments, so it is not always necessary to add a method for this case. If the type uses configurable human-readable output, define show(::IO, ::MIME"text/plain", ::T)
. For example, the type Day
uses 1 day
as the output for the MIME type text/plain', and `Day(1)
as the output of show
with two arguments.
Examples
julia> struct Day
n::Int
end
julia> Base.show(io::IO, ::MIME"text/plain", d::Day) = print(io, d.n, " day")
julia> Day(1)
1 day
Container types usually implement show
with three arguments by calling show(io, MIME"text/plain"(), x)
for the elements of x
, with :compact => true
set in 'IOContext`, passed as the first argument.
#
Base.Multimedia.showable
— Function
showable(mime, x)
Returns a boolean value indicating whether the object x
can be written as a given mime
type.
(By default, this is determined automatically by the very existence of the corresponding method show
for typeof(x)
. Some types provide custom showable
methods, for example, if the available MIME formats depend on the value of `x'.)
Examples
julia> showable(MIME("text/plain"), rand(5))
true
julia> showable("image/png", rand(5))
false
#
Base.repr
— Method
repr(mime, x; context=nothing)
Returns an AbstractString
or Vector' object{UInt8}
, which contains the representation of x
in the requested mime
type according to show(io, mime, x)
(if the appropriate show
method is unavailable, it is issued MethodError
). For MIME types with text representations (such as "text/html" or `"application/postscript"
, AbstractString
is returned, with binary data returned as Vector{UInt8}
. (The istextmime(mime)
function returns a value regardless of whether Julia processes this type of mime
as a text.)
The optional named argument context
can be assigned the pair :key=>value
or the IO
object or 'IOContext`, the attributes of which are used for the I/O stream passed to `show'.
In some cases, if x
is AbstractString
(for MIME text types) or Vector{UInt8}
(for binary MIME types), the repr
function assumes that x
already has the requested mime
format, and simply returns x'. This is not applicable for the MIME type `"text/plain"
. This method is used to transfer the raw data to `display(m::MIME, x)'.
In particular, repr("text/plain", x)
is usually a version of the "structural printout of the program code" for x
designed for human consumption. See also the description of the method repr(x)
, which returns a string corresponding to show(x)
, which may be closer to the way the value of x
is 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"
#
Base.Multimedia.MIME
— Type
MIME
A type representing a standard web data format. MIME stands for Multipurpose Internet Mail Extensions, as this standard was originally used to describe multimedia attachments in e-mail messages.
The 'MIME` object can be passed as the second argument to show
to request output in this format.
Examples
julia> show(stdout, MIME("text/plain"), "hi")
"hi"
As mentioned above, you can also define new display backends. For example, a module that can display PNG images in a window can register this feature in Julia, so that when called display(x)
for types with PNG representations, the image will be automatically displayed in the module window.
To define a new display backend, you must first create a subtype D
of the abstract class. AbstractDisplay
. Then, for each MIME type (string mime
) that can be displayed in D
, define the function display(d::D, ::MIME"mime", x) = ...
, which displays x
as this MIME type, usually by calling show(io, mime, x)
or repr(io, mime, x)
. If x
cannot be displayed as this MIME type, an error should occur. MethodError
. This happens automatically when show
or repr
is called. Finally, the function display(d::D, x)
should be defined, which requests showable(mime, x)
about the mime
types supported by D
and outputs the best one. If no supported MIME type is found for x
, a 'MethodError` error should occur. Similarly, some subtypes may override redisplay(d::D,...)
. (Again, to add new display methods (display
), you need to import Base.display'.) The return values of these functions depend on the implementation (since in some cases it may be useful to return a "descriptor" of a certain type). The display functions for `D
can then be called directly, but they can also be called automatically from display(x)
, simply by sending a new display to the display backend stack using the appropriate function.
#
Base.Multimedia.pushdisplay
— Function
pushdisplay(d::AbstractDisplay)
Passes the new mapping d
on top of the global stack of displays and backends. When display(x)
or display(mime, x)
is called, x
is displayed on the topmost compatible backend in the stack (that is, the topmost backend that does not output MethodError
).
#
Base.Multimedia.popdisplay
— Function
popdisplay()
popdisplay(d::AbstractDisplay)
Removes the topmost backend from the stack of displays and backends, or the topmost copy of `d' in the second option.
#
Base.Multimedia.TextDisplay
— Type
TextDisplay(io::IO)
Returns TextDisplay <: AbstractDisplay
, where all objects are displayed as the MIME type text/plain (by default), and the text representation is written to the specified input/output stream. (This is how objects are output in Julia’s REPL.)
#
Base.Multimedia.istextmime
— Function
istextmime(m::MIME)
Determines whether the MIME type is text data. It is assumed that MIME types are binary data, with the exception of a set of types that are obviously related to text data (possibly Unicode).
Examples
julia> istextmime(MIME("text/plain"))
true
julia> istextmime(MIME("image/png"))
false
Network I/O
#
Base.bytesavailable
— Function
bytesavailable(io)
Returns the number of bytes available for reading before reading from this stream; otherwise, the buffer is blocked.
Examples
julia> io = IOBuffer("JuliaLang is a GitHub organization");
julia> bytesavailable(io)
34
#
Base.ntoh
— Function
ntoh(x)
Converts the byte order for a value from the byte order in the network (reverse order) to the order used by the host.
#
Base.hton
— Function
hton(x)
Converts the byte order for a value from the byte order of the host to the order used by the network (reverse order).
#
Base.ltoh
— Function
ltoh(x)
Converts the byte order for a value from the direct byte order to the order used by the host.
#
Base.htol
— Function
htol(x)
Converts the byte order for a value from the host byte order to the forward order.
#
Base.ENDIAN_BOM
— Constant
ENDIAN_BOM
The 32-bit byte order label indicates the native byte order on the host computer. Computers with the reverse byte order will contain the value `0x04030201'. Computers with the reverse byte order will contain the value `0x01020304'.