I/O and Network

I/O and Network

General I/O

Base.STDOUTConstant.
STDOUT

Global variable referring to the standard out stream.

source
Base.STDERRConstant.
STDERR

Global variable referring to the standard error stream.

source
Base.STDINConstant.
STDIN

Global variable referring to the standard input stream.

source
Base.openFunction.
open(filename::AbstractString; keywords...) -> IOStream

Open a file in a mode specified by five boolean keyword arguments:

KeywordDesciptionDefault
readopen for reading!write
writeopen for writingtruncate | append
createcreate if non-existent!read & write | truncate | append
truncatetruncate to zero size!read & write
appendseek to endfalse

The default when no keywords are passed is to open files for reading only. Returns a stream for accessing the opened file.

source
open(filename::AbstractString, [mode::AbstractString]) -> IOStream

Alternate syntax for open, where a string-based mode specifier is used instead of the five booleans. The values of mode correspond to those from fopen(3) or Perl open, and are equivalent to setting the following boolean groups:

ModeDescriptionKeywords
rreadnone
wwrite, create, truncatewrite = true
awrite, create, appendappend = true
r+read, writeread = true, write = true
w+read, write, create, truncatetruncate = true, read = true
a+read, write, create, appendappend = true, read = true

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")
source
open(f::Function, args...; kwargs....)

Apply the function f to the result of open(args...; kwargs...) and close the resulting file descriptor upon completion.

Examples

julia> open("myfile.txt", "w") do io
           write(io, "Hello world!");
       end

julia> open(f->read(f, String), "myfile.txt")
"Hello world!"

julia> rm("myfile.txt")
source
open(command, mode::AbstractString="r", stdio=DevNull)

Start running command asynchronously, and return a tuple (stream,process). If mode is "r", then stream reads from the process's standard output and stdio optionally specifies the process's standard input stream. If mode is "w", then stream writes to the process's standard input and stdio optionally specifies the process's standard output stream.

source
open(f::Function, command, mode::AbstractString="r", stdio=DevNull)

Similar to open(command, mode, stdio), but calls f(stream) on the resulting process stream, then closes the input stream and waits for the process to complete. Returns the value returned by f.

source
Base.IOBufferType.
IOBuffer([data::AbstractVector{UInt8}]; keywords...) -> IOBuffer

Create 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; see open 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 implement sizehint!(data, size)).

When data is not given, the buffer will be both readable and writable 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
source
IOBuffer(string::String)

Create a read-only IOBuffer on the data underlying the given string.

Examples

julia> io = IOBuffer("Haho");

julia> String(take!(io))
"Haho"

julia> String(take!(io))
"Haho"
source
Base.take!Method.
take!(b::IOBuffer)

Obtain the contents of an IOBuffer as an array, without copying. Afterwards, the IOBuffer is reset to its initial state.

Examples

julia> io = IOBuffer();

julia> write(io, "JuliaLang is a GitHub organization.", "It has many members.")
55

julia> String(take!(io))
"JuliaLang is a GitHub organization.It has many members."
source
Base.fdioFunction.
fdio([name::AbstractString, ]fd::Integer[, own::Bool=false]) -> IOStream

Create an IOStream object from an integer file descriptor. If own is true, closing this object will close the underlying descriptor. By default, an IOStream is closed when it is garbage collected. name allows you to associate the descriptor with a named file.

source
Base.flushFunction.
flush(stream)

Commit all currently buffered writes to the given stream.

source
Base.closeFunction.
close(stream)

Close an I/O stream. Performs a flush first.

source
Base.writeFunction.
write(io::IO, x)
write(filename::AbstractString, 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.

You can write multiple values with the same write call. i.e. the following are equivalent:

write(io, x, y...)
write(io, x) + write(io, y...)

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> write(io, "Sometimes those members") + write(io, " write documentation.")
44

julia> String(take!(io))
"Sometimes those members write documentation."
source
Base.readFunction.
read(io::IO, T)

Read a single value of type T from io, in canonical binary representation.

read(io::IO, String)

Read the entirety of io, as a String.

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"
source
read(filename::AbstractString, args...)

Open a file and read its contents. args is passed to read: this is equivalent to open(io->read(io, args...), filename).

read(filename::AbstractString, String)

Read the entire contents of a file as a string.

source
read(s::IO, nb=typemax(Int))

Read at most nb bytes from s, returning a Vector{UInt8} of the bytes read.

source
read(s::IOStream, nb::Integer; all=true)

Read at most nb bytes from s, returning a Vector{UInt8} of the bytes read.

If all is true (the default), this function will block repeatedly trying to read all requested bytes, until an error or end-of-file occurs. If all is false, at most one read call is performed, and the amount of data returned is device-dependent. Note that not all stream types support the all option.

source
Base.read!Function.
read!(stream::IO, array::Union{Array, BitArray})
read!(filename::AbstractString, array::Union{Array, BitArray})

Read binary data from an I/O stream or file, filling in array.

source
Base.readbytes!Function.
readbytes!(stream::IO, b::AbstractVector{UInt8}, nb=length(b))

Read at most nb bytes from stream into b, returning the number of bytes read. The size of b will be increased if needed (i.e. if nb is greater than length(b) and enough bytes could be read), but it will never be decreased.

source
readbytes!(stream::IOStream, b::AbstractVector{UInt8}, nb=length(b); all::Bool=true)

Read at most nb bytes from stream into b, returning the number of bytes read. The size of b will be increased if needed (i.e. if nb is greater than length(b) and enough bytes could be read), but it will never be decreased.

See read for a description of the all option.

source
Base.unsafe_readFunction.
unsafe_read(io::IO, ref, nbytes::UInt)

Copy nbytes from the IO stream object into ref (converted to a pointer).

It is recommended that subtypes T<:IO override the following method signature to provide more efficient implementations: unsafe_read(s::T, p::Ptr{UInt8}, n::UInt)

source
Base.unsafe_writeFunction.
unsafe_write(io::IO, ref, nbytes::UInt)

Copy nbytes from ref (converted to a pointer) into the IO object.

It is recommended that subtypes T<:IO override the following method signature to provide more efficient implementations: unsafe_write(s::T, p::Ptr{UInt8}, n::UInt)

source
Base.positionFunction.
position(s)

Get the current position of a 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
source
Base.seekFunction.
seek(s, pos)

Seek a stream to the given position.

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)
source
Base.seekstartFunction.
seekstart(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)
source
Base.seekendFunction.
seekend(s)

Seek a stream to its end.

source
Base.skipFunction.
skip(s, offset)

Seek a stream 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)
source
Base.markFunction.
mark(s)

Add a mark at the current position of stream s. Return the marked position.

See also unmark, reset, ismarked.

source
Base.unmarkFunction.
unmark(s)

Remove a mark from stream s. Return true if the stream was marked, false otherwise.

See also mark, reset, ismarked.

source
Base.resetFunction.
reset(s)

Reset a stream s to a previously marked position, and remove the mark. Return the previously marked position. Throw an error if the stream is not marked.

See also mark, unmark, ismarked.

source
Base.ismarkedFunction.
ismarked(s)

Return true if stream s is marked.

See also mark, unmark, reset.

source
Base.eofFunction.
eof(stream) -> Bool

Test 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 return false. Therefore it is always safe to read one byte after seeing eof return false. eof will return false as long as buffered data is still available, even if the remote end of a connection is closed.

source
Base.isreadonlyFunction.
isreadonly(io) -> Bool

Determine whether a stream is read-only.

Examples

julia> io = IOBuffer("JuliaLang is a GitHub organization");

julia> isreadonly(io)
true

julia> io = IOBuffer();

julia> isreadonly(io)
false
source
Base.iswritableFunction.
iswritable(io) -> Bool

Return true if the specified IO object is writable (if that can be determined).

Examples

julia> open("myfile.txt", "w") do io
           write(io, "Hello world!");
           iswritable(io)
       end
true

julia> open("myfile.txt", "r") do io
           iswritable(io)
       end
false

julia> rm("myfile.txt")
source
Base.isreadableFunction.
isreadable(io) -> Bool

Return true if the specified IO object is readable (if that can be determined).

Examples

julia> open("myfile.txt", "w") do io
           write(io, "Hello world!");
           isreadable(io)
       end
false

julia> open("myfile.txt", "r") do io
           isreadable(io)
       end
true

julia> rm("myfile.txt")
source
Base.isopenFunction.
isopen(object) -> Bool

Determine whether an object - such as a stream, timer, or mmap – 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, use eof to check for the ability to read data. Use the FileWatching package to be notified when a stream might be writable or readable.

Examples

julia> io = open("my_file.txt", "w+");

julia> isopen(io)
true

julia> close(io)

julia> isopen(io)
false
source
print_shortest(io::IO, x)

Print the shortest possible representation, with the minimum number of consecutive non-zero digits, of number x, ensuring that it would parse to the exact same number.

source
Base.fdFunction.
fd(stream)

Return the file descriptor backing the stream or file. Note that this function only applies to synchronous File's and IOStream's not to any of the asynchronous streams.

source
Base.redirect_stdoutFunction.
redirect_stdout([stream]) -> (rd, wr)

Create a pipe to which all C and Julia level STDOUT output will be redirected. Returns a tuple (rd, wr) representing the pipe ends. Data written to STDOUT may now be read from the rd end of the pipe. The wr end is given for convenience in case the old STDOUT object was cached by the user and needs to be replaced elsewhere.

Note

stream must be a TTY, a Pipe, or a TCPSocket.

source
redirect_stdout(f::Function, stream)

Run the function f while redirecting STDOUT to stream. Upon completion, STDOUT is restored to its prior setting.

Note

stream must be a TTY, a Pipe, or a TCPSocket.

source
Base.redirect_stderrFunction.
redirect_stderr([stream]) -> (rd, wr)

Like redirect_stdout, but for STDERR.

Note

stream must be a TTY, a Pipe, or a TCPSocket.

source
redirect_stderr(f::Function, stream)

Run the function f while redirecting STDERR to stream. Upon completion, STDERR is restored to its prior setting.

Note

stream must be a TTY, a Pipe, or a TCPSocket.

source
Base.redirect_stdinFunction.
redirect_stdin([stream]) -> (rd, wr)

Like redirect_stdout, but for STDIN. Note that the order of the return tuple is still (rd, wr), i.e. data to be read from STDIN may be written to wr.

Note

stream must be a TTY, a Pipe, or a TCPSocket.

source
redirect_stdin(f::Function, stream)

Run the function f while redirecting STDIN to stream. Upon completion, STDIN is restored to its prior setting.

Note

stream must be a TTY, a Pipe, or a TCPSocket.

source
Base.readchompFunction.
readchomp(x)

Read the entirety of x as a string and remove a single trailing newline if there is one. Equivalent to chomp(read(x, String)).

Examples

julia> open("my_file.txt", "w") do io
           write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
       end;

julia> readchomp("my_file.txt")
"JuliaLang is a GitHub organization.\nIt has many members."

julia> rm("my_file.txt");
source
Base.truncateFunction.
truncate(file,n)

Resize the file or buffer given by the first argument to exactly n 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.")
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."
source
Base.skipcharsFunction.
skipchars(predicate, io::IO; linecomment=nothing)

Advance the stream io such that the next-read character will be the first remaining for which predicate returns false. If the keyword argument linecomment 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"
source
Base.countlinesFunction.
countlines(io::IO; eol::Char = '\n')

Read io 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 of io is counted even if it does not end with the EOL, matching the length returned by eachline and readlines.

Examples

julia> io = IOBuffer("JuliaLang is a GitHub organization.
");

julia> countlines(io)
1

julia> io = IOBuffer("JuliaLang is a GitHub organization.");

julia> countlines(io)
1

julia> countlines(io, eol = '.')
1
source
Base.PipeBufferFunction.
PipeBuffer(data::Vector{UInt8}=UInt8[]; maxsize::Integer = typemax(Int))

An IOBuffer that allows reading and performs writes by appending. Seeking and truncating are not supported. See IOBuffer for the available constructors. If data is given, creates a PipeBuffer to operate on a data vector, optionally specifying a size beyond which the underlying Array may not be grown.

source
Base.readavailableFunction.
readavailable(stream)

Read all available data on the stream, blocking the task only if no data is available. The result is a Vector{UInt8,1}.

source
Base.IOContextType.
IOContext

IOContext provides a mechanism for passing output configuration settings among show methods.

In short, it is an immutable dictionary that is a subclass of IO. It supports standard dictionary operations such as getindex, and can also be used as an I/O stream.

source
Base.IOContextMethod.
IOContext(io::IO, KV::Pair...)

Create an IOContext that wraps a given stream, adding the specified key=>value pairs to the properties of that stream (note that io can itself be an IOContext).

  • use (key => value) in dict to see if this particular combination is in the properties set

  • use get(dict, key, default) to retrieve the most recent value for a particular key

The following properties are in common use:

  • :compact: Boolean specifying that small values should be printed more compactly, e.g. that numbers should be printed with fewer digits. This is set when printing array elements.

  • :limit: Boolean specifying that containers should be truncated, e.g. showing in place of most elements.

  • :displaysize: A Tuple{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 the displaysize function.

  • :typeinfo: a Type 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 to Float16).

  • :color: Boolean specifying whether ANSI color/escape codes are supported/expected. By default, this is determined by whether io is a compatible terminal and by any --color command-line flag when julia was launched.

Examples

julia> io = IOBuffer();

julia> printstyled(IOContext(io, :color => true), "string", color=:red)

julia> String(take!(io))
"string"

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
source
Base.IOContextMethod.
IOContext(io::IO, context::IOContext)

Create an IOContext that wraps an alternate IO but inherits the properties of context.

source

Text I/O

Base.showMethod.
show(x)

Write an informative text representation of a value to the current output stream. New types should overload show(io, x) where the first argument is a stream. The representation used by show generally includes Julia-specific formatting and type information.

source
Base.showcompactFunction.
showcompact(x)
showcompact(io::IO, x)

Show a compact representation of a value to io. If io is not specified, the default is to print to STDOUT.

This is used for printing array elements without repeating type information (which would be redundant with that printed once for the whole array), and without line breaks inside the representation of an element.

To offer a compact representation different from its standard one, a custom type should test get(io, :compact, false) in its normal show method.

Examples

julia> A = [1. 2.; 3. 4]
2×2 Array{Float64,2}:
 1.0  2.0
 3.0  4.0

julia> showcompact(A)
[1.0 2.0; 3.0 4.0]
source
Base.summaryFunction.
summary(io::IO, x)
str = summary(x)

Print to a stream io, or return a string str, giving a brief description of a value. By default returns string(typeof(x)), e.g. Int64.

For arrays, returns a string of size and type info, e.g. 10-element Array{Int64,1}.

Examples

julia> summary(1)
"Int64"

julia> summary(zeros(2))
"2-element Array{Float64,1}"
source
Base.printFunction.
print([io::IO], xs...)

Write to io (or to the default output stream STDOUT if io is not given) a canonical (un-decorated) text representation of values xs if there is one, otherwise call show. The representation used by print includes minimal formatting and tries to avoid Julia-specific details.

Examples

julia> print("Hello World!")
Hello World!
julia> io = IOBuffer();

julia> print(io, "Hello", ' ', :World!)

julia> String(take!(io))
"Hello World!"
source
Base.printlnFunction.
println([io::IO], xs...)

Print (using print) xs followed by a newline. If io is not supplied, prints to STDOUT.

Examples

julia> println("Hello, world")
Hello, world

julia> io = IOBuffer();

julia> println(io, "Hello, world")

julia> String(take!(io))
"Hello, world\n"
source
Base.printstyledFunction.
printstyled([io], xs...; bold::Bool=false, color::Union{Symbol,Int}=:normal)

Print xs in a color specified as a symbol or integer, optionally in bold.

color may take any of the values :normal, :default, :bold, :black, :blink, :blue, :cyan, :green, :hidden, :light_black, :light_blue, :light_cyan, :light_green, :light_magenta, :light_red, :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. If the keyword bold is given as true, the result will be printed in bold.

source
Base.sprintFunction.
sprint(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.

The optional keyword argument context can be set to :key=>value pair or an IO or IOContext object whose attributes are used for the I/O stream passed to f. The optional sizehint is a suggersted (in bytes) to allocate for the buffer used to write the string.

Examples

julia> sprint(showcompact, 66.66666)
"66.6667"
source
Base.showerrorFunction.
showerror(io, e)

Show a descriptive representation of an exception object e. This method is used to display the exception after a call to throw.

Examples

julia> struct MyException <: Exception
           msg::AbstractString
       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
source
Base.dumpFunction.
dump(x; maxdepth=8)

Show every part of the representation of a value.

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

Nested data structures are truncated at maxdepth.

julia> struct DeeplyNested
           xs::Vector{DeeplyNested}
       end;

julia> x = DeeplyNested([]);

julia> push!(x.xs, x);

julia> dump(x)
DeeplyNested
  xs: Array{DeeplyNested}((1,))
    1: DeeplyNested
      xs: Array{DeeplyNested}((1,))
        1: DeeplyNested
          xs: Array{DeeplyNested}((1,))
            1: DeeplyNested
              xs: Array{DeeplyNested}((1,))
                1: DeeplyNested

julia> dump(x, maxdepth=2)
DeeplyNested
  xs: Array{DeeplyNested}((1,))
    1: DeeplyNested
source
Base.Meta.@dumpMacro.
@dump expr

Show every part of the representation of the given expression. Equivalent to dump(:(expr)).

source
Base.readlineFunction.
readline(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 to STDIN). 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. When keep is false (as it is by default), these trailing newline characters are removed from the line before it is returned. When keep is true, they are returned as part of the line.

Examples

julia> open("my_file.txt", "w") do io
           write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
       end
57

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")
source
Base.readuntilFunction.
readuntil(stream::IO, delim; keep::Bool = false)
readuntil(filename::AbstractString, delim; keep::Bool = false)

Read a string from an I/O stream or a file, up to the given delimiter. The delimiter can be a UInt8, Char, string, or vector. Keyword argument keep controls whether the delimiter is included in the result. The text is assumed to be encoded in UTF-8.

Examples

julia> open("my_file.txt", "w") do io
           write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
       end
57

julia> readuntil("my_file.txt", 'L')
"JuliaL"

julia> readuntil("my_file.txt", '.')
"JuliaLang is a GitHub organization."

julia> rm("my_file.txt")
source
Base.readlinesFunction.
readlines(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 reading readline repeatedly with the same arguments and saving the resulting lines as a vector of strings.

Examples

julia> open("my_file.txt", "w") do io
           write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
       end
57

julia> readlines("my_file.txt")
2-element Array{String,1}:
 "JuliaLang is a GitHub organization."
 "It has many members."

julia> readlines("my_file.txt", keep=true)
2-element Array{String,1}:
 "JuliaLang is a GitHub organization.\n"
 "It has many members.\n"

julia> rm("my_file.txt")
source
Base.eachlineFunction.
eachline(io::IO=STDIN; keep::Bool=false)
eachline(filename::AbstractString; keep::Bool=false)

Create an iterable EachLine object that will yield each line from an I/O stream or a file. Iteration calls readline on the stream argument repeatedly with keep 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 the EachLine object is garbage collected.

Examples

julia> open("my_file.txt", "w") do io
           write(io, "JuliaLang is a GitHub organization.\n It has many members.\n");
       end;

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");
source
Base.displaysizeFunction.
displaysize([io::IO]) -> (lines, columns)

Return the nominal size of the screen that may be used for rendering output to this IO object. If no input is provided, the environment variables LINES and COLUMNS 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)
source

Multimedia I/O

Just as text output is performed by print and user-defined types can indicate their textual representation by overloading show, Julia provides a standardized mechanism for rich multimedia output (such as images, formatted text, or even audio and video), consisting of three parts:

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.display
Base.Multimedia.redisplay
Base.Multimedia.displayable
Base.show(::Any, ::Any, ::Any)
Base.Multimedia.mimewritable
Base.repr(::Any, ::Any)

As 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 calling display(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 subtype D of the abstract class AbstractDisplay. Then, for each MIME type (mime string) that can be displayed on D, one should define a function display(d::D, ::MIME"mime", x) = ... that displays x as that MIME type, usually by calling show(io, mime, x) or repr(io, mime, x). A MethodError should be thrown if x cannot be displayed as that MIME type; this is automatic if one calls show or repr. Finally, one should define a function display(d::D, x) that queries mimewritable(mime, x) for the mime types supported by D and displays the "best" one; a MethodError should be thrown if no supported MIME types are found for x. Similarly, some subtypes may wish to override redisplay(d::D, ...). (Again, one should import Base.display to add new methods to display.) 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 for D can then be called directly, but they can also be invoked automatically from display(x) simply by pushing a new display onto the display-backend stack with:

pushdisplay(d::AbstractDisplay)

Pushes a new display d on top of the global display-backend stack. Calling display(x) or display(mime, x) will display x on the topmost compatible backend in the stack (i.e., the topmost backend that does not throw a MethodError).

source
popdisplay()
popdisplay(d::AbstractDisplay)

Pop the topmost backend off of the display-backend stack, or the topmost copy of d in the second variant.

source
TextDisplay(io::IO)

Returns a TextDisplay <: 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.)

source
istextmime(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"))
true

julia> istextmime(MIME("img/png"))
false
source

Network I/O

Base.connectMethod.
connect([host], port::Integer) -> TCPSocket

Connect to the host host on port port.

source
Base.connectMethod.
connect(path::AbstractString) -> PipeEndpoint

Connect to the named pipe / UNIX domain socket at path.

source
Base.listenMethod.
listen([addr, ]port::Integer; backlog::Integer=BACKLOG_DEFAULT) -> TCPServer

Listen on port on the address specified by addr. By default this listens on localhost only. To listen on all interfaces pass IPv4(0) or IPv6(0) as appropriate. backlog determines how many connections can be pending (not having called accept) before the server will begin to reject them. The default value of backlog is 511.

source
Base.listenMethod.
listen(path::AbstractString) -> PipeServer

Create and listen on a named pipe / UNIX domain socket.

source
Base.getaddrinfoFunction.
getalladdrinfo(host::AbstractString, IPAddr=IPv4) -> IPAddr

Gets the first IP address of the host of the specified IPAddr type. Uses the operating system's underlying getaddrinfo implementation, which may do a DNS lookup.

source
Base.getalladdrinfoFunction.
getalladdrinfo(host::AbstractString) -> Vector{IPAddr}

Gets all of the IP addresses of the host. Uses the operating system's underlying getaddrinfo implementation, which may do a DNS lookup.

source
Base.getnameinfoFunction.
getnameinfo(host::IPAddr) -> String

Performs a reverse-lookup for IP address to return a hostname and service using the operating system's underlying getnameinfo implementation.

source
Base.getsocknameFunction.
getsockname(sock::Union{TCPServer, TCPSocket}) -> (IPAddr, UInt16)

Get the IP address and port that the given socket is bound to.

source
Base.getpeernameFunction.
getpeername(sock::TCPSocket) -> (IPAddr, UInt16)

Get the IP address and port of the remote endpoint that the given socket is connected to. Valid only for connected TCP sockets.

source
Base.IPv4Type.
IPv4(host::Integer) -> IPv4

Returns an IPv4 object from ip address host formatted as an Integer.

julia> IPv4(3223256218)
ip"192.30.252.154"
source
Base.IPv6Type.
IPv6(host::Integer) -> IPv6

Returns an IPv6 object from ip address host formatted as an Integer.

julia> IPv6(3223256218)
ip"::c01e:fc9a"
source
Base.TCPSocketType.
TCPSocket(; delay=true)

Open a TCP socket using libuv. If delay is true, libuv delays creation of the socket's file descriptor till the first bind call. TCPSocket has various fields to denote the state of the socket as well as its send/receive buffers.

source
Base.UDPSocketType.
UDPSocket()

Open a UDP socket using libuv. UDPSocket has various fields to denote the state of the socket.

source
Base.bytesavailableFunction.
bytesavailable(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)
34
source
Base.acceptFunction.
accept(server[,client])

Accepts a connection on the given server and returns a connection to the client. An uninitialized client stream may be provided, in which case it will be used instead of creating a new stream.

source
Base.listenanyFunction.
listenany([host::IPAddr,] port_hint) -> (UInt16, TCPServer)

Create a TCPServer on any port, using hint as a starting point. Returns a tuple of the actual port that the server was created on and the server itself.

source
Base.bindFunction.
bind(socket::Union{UDPSocket, TCPSocket}, host::IPAddr, port::Integer; ipv6only=false, reuseaddr=false, kws...)

Bind socket to the given host:port. Note that 0.0.0.0 will listen on all devices.

  • The ipv6only parameter disables dual stack mode. If ipv6only=true, only an IPv6 stack is created.

  • If reuseaddr=true, multiple threads or processes can bind to the same address without error if they all set reuseaddr=true, but only the last to bind will receive any traffic.

source
bind(chnl::Channel, task::Task)

Associate the lifetime of chnl with a task. Channel chnl is automatically closed when the task terminates. Any uncaught exception in the task is propagated to all waiters on chnl.

The chnl object can be explicitly closed independent of task termination. Terminating tasks have no effect on already closed Channel objects.

When a channel is bound to multiple tasks, the first task to terminate will close the channel. When multiple channels are bound to the same task, termination of the task will close all of the bound channels.

Examples

julia> c = Channel(0);

julia> task = @schedule foreach(i->put!(c, i), 1:4);

julia> bind(c,task);

julia> for i in c
           @show i
       end;
i = 1
i = 2
i = 3
i = 4

julia> isopen(c)
false
julia> c = Channel(0);

julia> task = @schedule (put!(c,1);error("foo"));

julia> bind(c,task);

julia> take!(c)
1

julia> put!(c,1);
ERROR: foo
Stacktrace:
[...]
source
Base.sendFunction.
send(socket::UDPSocket, host, port::Integer, msg)

Send msg over socket to host:port.

source
Base.recvFunction.
recv(socket::UDPSocket)

Read a UDP packet from the specified socket, and return the bytes received. This call blocks.

source
Base.recvfromFunction.
recvfrom(socket::UDPSocket) -> (address, data)

Read a UDP packet from the specified socket, returning a tuple of (address, data), where address will be either IPv4 or IPv6 as appropriate.

source
Base.setoptFunction.
setopt(sock::UDPSocket; multicast_loop = nothing, multicast_ttl=nothing, enable_broadcast=nothing, ttl=nothing)

Set UDP socket options.

  • multicast_loop: loopback for multicast packets (default: true).

  • multicast_ttl: TTL for multicast packets (default: nothing).

  • enable_broadcast: flag must be set to true if socket will be used for broadcast messages, or else the UDP system will return an access error (default: false).

  • ttl: Time-to-live of packets sent on the socket (default: nothing).

source
Base.ntohFunction.
ntoh(x)

Converts the endianness of a value from Network byte order (big-endian) to that used by the Host.

source
Base.htonFunction.
hton(x)

Converts the endianness of a value from that used by the Host to Network byte order (big-endian).

source
Base.ltohFunction.
ltoh(x)

Converts the endianness of a value from Little-endian to that used by the Host.

source
Base.htolFunction.
htol(x)

Converts the endianness of a value from that used by the Host to Little-endian.

source
Base.ENDIAN_BOMConstant.
ENDIAN_BOM

The 32-bit byte-order-mark indicates the native byte order of the host machine. Little-endian machines will contain the value 0x04030201. Big-endian machines will contain the value 0x01020304.

source