I/O 与网络

通用 I/O

Base.stdout — Constant.

  1. stdout

Global variable referring to the standard out stream.

source

Base.stderr — Constant.

  1. stderr

Global variable referring to the standard error stream.

source

Base.stdin — Constant.

  1. stdin

Global variable referring to the standard input stream.

source

Base.open — Function.

  1. open(filename::AbstractString; keywords...) -> IOStream

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

KeywordDescriptionDefault
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

  1. 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

  1. julia> io = open("myfile.txt", "w");
  2. julia> write(io, "Hello world!");
  3. julia> close(io);
  4. julia> io = open("myfile.txt", "r");
  5. julia> read(io, String)
  6. "Hello world!"
  7. julia> write(io, "This file is read only")
  8. ERROR: ArgumentError: write failed, IOStream is not writeable
  9. [...]
  10. julia> close(io)
  11. julia> io = open("myfile.txt", "a");
  12. julia> write(io, "This stream is not read only")
  13. 28
  14. julia> close(io)
  15. julia> rm("myfile.txt")

source

  1. 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

  1. julia> open("myfile.txt", "w") do io
  2. write(io, "Hello world!")
  3. end;
  4. julia> open(f->read(f, String), "myfile.txt")
  5. "Hello world!"
  6. julia> rm("myfile.txt")

source

  1. open(command, stdio=devnull; write::Bool = false, read::Bool = !write)

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

source

  1. 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.IOBuffer — Type.

  1. 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

  1. julia> io = IOBuffer();
  2. julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
  3. 56
  4. julia> String(take!(io))
  5. "JuliaLang is a GitHub organization. It has many members."
  6. julia> io = IOBuffer(b"JuliaLang is a GitHub organization.")
  7. IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=35, maxsize=Inf, ptr=1, mark=-1)
  8. julia> read(io, String)
  9. "JuliaLang is a GitHub organization."
  10. julia> write(io, "This isn't writable.")
  11. ERROR: ArgumentError: ensureroom failed, IOBuffer is not writeable
  12. julia> io = IOBuffer(UInt8[], read=true, write=true, maxsize=34)
  13. IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=34, ptr=1, mark=-1)
  14. julia> write(io, "JuliaLang is a GitHub organization.")
  15. 34
  16. julia> String(take!(io))
  17. "JuliaLang is a GitHub organization"
  18. julia> length(read(IOBuffer(b"data", read=true, truncate=false)))
  19. 4
  20. julia> length(read(IOBuffer(b"data", read=true, truncate=true)))
  21. 0

source

  1. IOBuffer(string::String)

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

Examples

  1. julia> io = IOBuffer("Haho");
  2. julia> String(take!(io))
  3. "Haho"
  4. julia> String(take!(io))
  5. "Haho"

source

Base.take! — Method.

  1. take!(b::IOBuffer)

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

Examples

  1. julia> io = IOBuffer();
  2. julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
  3. 56
  4. julia> String(take!(io))
  5. "JuliaLang is a GitHub organization. It has many members."

source

Base.fdio — Function.

  1. 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.flush — Function.

  1. flush(stream)

Commit all currently buffered writes to the given stream.

source

Base.close — Function.

  1. close(stream)

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

source

Base.write — Function.

  1. write(io::IO, x)
  2. 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. See also print to write a text representation (with an encoding that may depend upon io).

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

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

Examples

  1. julia> io = IOBuffer();
  2. julia> write(io, "JuliaLang is a GitHub organization.", " It has many members.")
  3. 56
  4. julia> String(take!(io))
  5. "JuliaLang is a GitHub organization. It has many members."
  6. julia> write(io, "Sometimes those members") + write(io, " write documentation.")
  7. 44
  8. julia> String(take!(io))
  9. "Sometimes those members write documentation."

source

Base.read — Function.

  1. read(io::IO, T)

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

  1. read(io::IO, String)

Read the entirety of io, as a String.

Examples

  1. julia> io = IOBuffer("JuliaLang is a GitHub organization");
  2. julia> read(io, Char)
  3. 'J': ASCII/Unicode U+004a (category Lu: Letter, uppercase)
  4. julia> io = IOBuffer("JuliaLang is a GitHub organization");
  5. julia> read(io, String)
  6. "JuliaLang is a GitHub organization"

source

  1. 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).

  1. read(filename::AbstractString, String)

Read the entire contents of a file as a string.

source

  1. read(s::IO, nb=typemax(Int))

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

source

  1. 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

  1. read(command::Cmd)

Run command and return the resulting output as an array of bytes.

source

  1. read(command::Cmd, String)

Run command and return the resulting output as a String.

source

Base.read! — Function.

  1. read!(stream::IO, array::Union{Array, BitArray})
  2. read!(filename::AbstractString, array::Union{Array, BitArray})

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

source

Base.readbytes! — Function.

  1. 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

  1. 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_read — Function.

  1. 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_write — Function.

  1. 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.position — Function.

  1. position(s)

Get the current position of a stream.

Examples

  1. julia> io = IOBuffer("JuliaLang is a GitHub organization.");
  2. julia> seek(io, 5);
  3. julia> position(io)
  4. 5
  5. julia> skip(io, 10);
  6. julia> position(io)
  7. 15
  8. julia> seekend(io);
  9. julia> position(io)
  10. 35

source

Base.seek — Function.

  1. seek(s, pos)

Seek a stream to the given position.

Examples

  1. julia> io = IOBuffer("JuliaLang is a GitHub organization.");
  2. julia> seek(io, 5);
  3. julia> read(io, Char)
  4. 'L': ASCII/Unicode U+004c (category Lu: Letter, uppercase)

source

Base.seekstart — Function.

  1. seekstart(s)

Seek a stream to its beginning.

Examples

  1. julia> io = IOBuffer("JuliaLang is a GitHub organization.");
  2. julia> seek(io, 5);
  3. julia> read(io, Char)
  4. 'L': ASCII/Unicode U+004c (category Lu: Letter, uppercase)
  5. julia> seekstart(io);
  6. julia> read(io, Char)
  7. 'J': ASCII/Unicode U+004a (category Lu: Letter, uppercase)

source

Base.seekend — Function.

  1. seekend(s)

Seek a stream to its end.

source

Base.skip — Function.

  1. skip(s, offset)

Seek a stream relative to the current position.

Examples

  1. julia> io = IOBuffer("JuliaLang is a GitHub organization.");
  2. julia> seek(io, 5);
  3. julia> skip(io, 10);
  4. julia> read(io, Char)
  5. 'G': ASCII/Unicode U+0047 (category Lu: Letter, uppercase)

source

Base.mark — Function.

  1. mark(s)

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

See also unmark, reset, ismarked.

source

Base.unmark — Function.

  1. unmark(s)

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

See also mark, reset, ismarked.

source

Base.reset — Function.

  1. 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.ismarked — Function.

  1. ismarked(s)

Return true if stream s is marked.

See also mark, unmark, reset.

source

Base.eof — Function.

  1. 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.isreadonly — Function.

  1. isreadonly(io) -> Bool

Determine whether a stream is read-only.

Examples

  1. julia> io = IOBuffer("JuliaLang is a GitHub organization");
  2. julia> isreadonly(io)
  3. true
  4. julia> io = IOBuffer();
  5. julia> isreadonly(io)
  6. false

source

Base.iswritable — Function.

  1. iswritable(io) -> Bool

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

Examples

  1. julia> open("myfile.txt", "w") do io
  2. print(io, "Hello world!");
  3. iswritable(io)
  4. end
  5. true
  6. julia> open("myfile.txt", "r") do io
  7. iswritable(io)
  8. end
  9. false
  10. julia> rm("myfile.txt")

source

Base.isreadable — Function.

  1. isreadable(io) -> Bool

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

Examples

  1. julia> open("myfile.txt", "w") do io
  2. print(io, "Hello world!");
  3. isreadable(io)
  4. end
  5. false
  6. julia> open("myfile.txt", "r") do io
  7. isreadable(io)
  8. end
  9. true
  10. julia> rm("myfile.txt")

source

Base.isopen — Function.

  1. isopen(object) -> Bool

Determine 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, 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

  1. julia> io = open("my_file.txt", "w+");
  2. julia> isopen(io)
  3. true
  4. julia> close(io)
  5. julia> isopen(io)
  6. false

source

Base.Grisu.print_shortest — Function.

  1. 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.fd — Function.

  1. 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_stdout — Function.

  1. 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.

If called with the optional stream argument, then returns stream itself.

Note

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

source

Base.redirect_stdout — Method.

  1. 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 socket.

source

Base.redirect_stderr — Function.

  1. redirect_stderr([stream]) -> (rd, wr)

Like redirect_stdout, but for stderr.

Note

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

source

Base.redirect_stderr — Method.

  1. 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 socket.

source

Base.redirect_stdin — Function.

  1. 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 socket.

source

Base.redirect_stdin — Method.

  1. 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 socket.

source

Base.readchomp — Function.

  1. 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

  1. julia> open("my_file.txt", "w") do io
  2. write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
  3. end;
  4. julia> readchomp("my_file.txt")
  5. "JuliaLang is a GitHub organization.\nIt has many members."
  6. julia> rm("my_file.txt");

source

Base.truncate — Function.

  1. 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

  1. julia> io = IOBuffer();
  2. julia> write(io, "JuliaLang is a GitHub organization.")
  3. 35
  4. julia> truncate(io, 15)
  5. IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=15, maxsize=Inf, ptr=16, mark=-1)
  6. julia> String(take!(io))
  7. "JuliaLang is a "
  8. julia> io = IOBuffer();
  9. julia> write(io, "JuliaLang is a GitHub organization.");
  10. julia> truncate(io, 40);
  11. julia> String(take!(io))
  12. "JuliaLang is a GitHub organization.\0\0\0\0\0"

source

Base.skipchars — Function.

  1. 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

  1. julia> buf = IOBuffer(" text")
  2. IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=8, maxsize=Inf, ptr=1, mark=-1)
  3. julia> skipchars(isspace, buf)
  4. IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=8, maxsize=Inf, ptr=5, mark=-1)
  5. julia> String(readavailable(buf))
  6. "text"

source

Base.countlines — Function.

  1. countlines(io::IO; eol::AbstractChar = '\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

  1. julia> io = IOBuffer("JuliaLang is a GitHub organization.\n");
  2. julia> countlines(io)
  3. 1
  4. julia> io = IOBuffer("JuliaLang is a GitHub organization.");
  5. julia> countlines(io)
  6. 1
  7. julia> countlines(io, eol = '.')
  8. 0

source

Base.PipeBuffer — Function.

  1. 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.readavailable — Function.

  1. 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.IOContext — Type.

  1. 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.IOContext — Method.

  1. 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 io to see if this particular combination is in the properties set
  • use get(io, key, default) to retrieve the most recent value for a particular keyThe 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
  1. julia> io = IOBuffer();
  2. julia> printstyled(IOContext(io, :color => true), "string", color=:red)
  3. julia> String(take!(io))
  4. "\e[31mstring\e[39m"
  5. julia> printstyled(io, "string", color=:red)
  6. julia> String(take!(io))
  7. "string"
  1. julia> print(IOContext(stdout, :compact => false), 1.12341234)
  2. 1.12341234
  3. julia> print(IOContext(stdout, :compact => true), 1.12341234)
  4. 1.12341
  1. julia> function f(io::IO)
  2. if get(io, :short, false)
  3. print(io, "short")
  4. else
  5. print(io, "loooooong")
  6. end
  7. end
  8. f (generic function with 1 method)
  9. julia> f(stdout)
  10. loooooong
  11. julia> f(IOContext(stdout, :short => true))
  12. short

source

Base.IOContext — Method.

  1. IOContext(io::IO, context::IOContext)

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

source

文本 I/O

Base.show — Method.

  1. 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.summary — Function.

  1. summary(io::IO, x)
  2. 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

  1. julia> summary(1)
  2. "Int64"
  3. julia> summary(zeros(2))
  4. "2-element Array{Float64,1}"

source

Base.print — Function.

  1. 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.

Printing nothing is not allowed and throws an error.

Examples

  1. julia> print("Hello World!")
  2. Hello World!
  3. julia> io = IOBuffer();
  4. julia> print(io, "Hello", ' ', :World!)
  5. julia> String(take!(io))
  6. "Hello World!"

source

Base.println — Function.

  1. println([io::IO], xs...)

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

Examples

  1. julia> println("Hello, world")
  2. Hello, world
  3. julia> io = IOBuffer();
  4. julia> println(io, "Hello, world")
  5. julia> String(take!(io))
  6. "Hello, world\n"

source

Base.printstyled — Function.

  1. 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.sprint — Function.

  1. 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. context can be either an IOContext whose properties will be used, or a Pair specifying a property and its value. sizehint suggests the capacity of the buffer (in bytes).

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 suggested size (in bytes) to allocate for the buffer used to write the string.

Examples

  1. julia> sprint(show, 66.66666; context=:compact => true)
  2. "66.6667"
  3. julia> sprint(showerror, BoundsError([1], 100))
  4. "BoundsError: attempt to access 1-element Array{Int64,1} at index [100]"

source

Base.showerror — Function.

  1. 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

  1. julia> struct MyException <: Exception
  2. msg::AbstractString
  3. end
  4. julia> function Base.showerror(io::IO, err::MyException)
  5. print(io, "MyException: ")
  6. print(io, err.msg)
  7. end
  8. julia> err = MyException("test exception")
  9. MyException("test exception")
  10. julia> sprint(showerror, err)
  11. "MyException: test exception"
  12. julia> throw(MyException("test exception"))
  13. ERROR: MyException: test exception

source

Base.dump — Function.

  1. dump(x; maxdepth=8)

Show every part of the representation of a value. The depth of the output is truncated at maxdepth.

Examples

  1. julia> struct MyStruct
  2. x
  3. y
  4. end
  5. julia> x = MyStruct(1, (2,3));
  6. julia> dump(x)
  7. MyStruct
  8. x: Int64 1
  9. y: Tuple{Int64,Int64}
  10. 1: Int64 2
  11. 2: Int64 3
  12. julia> dump(x; maxdepth = 1)
  13. MyStruct
  14. x: Int64 1
  15. y: Tuple{Int64,Int64}

source

Base.Meta.@dump — Macro.

  1. @dump expr

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

source

Base.readline — Function.

  1. readline(io::IO=stdin; keep::Bool=false)
  2. 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

  1. julia> open("my_file.txt", "w") do io
  2. write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
  3. end
  4. 57
  5. julia> readline("my_file.txt")
  6. "JuliaLang is a GitHub organization."
  7. julia> readline("my_file.txt", keep=true)
  8. "JuliaLang is a GitHub organization.\n"
  9. julia> rm("my_file.txt")

source

Base.readuntil — Function.

  1. readuntil(stream::IO, delim; keep::Bool = false)
  2. 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, AbstractChar, 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

  1. julia> open("my_file.txt", "w") do io
  2. write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
  3. end
  4. 57
  5. julia> readuntil("my_file.txt", 'L')
  6. "Julia"
  7. julia> readuntil("my_file.txt", '.', keep = true)
  8. "JuliaLang is a GitHub organization."
  9. julia> rm("my_file.txt")

source

Base.readlines — Function.

  1. readlines(io::IO=stdin; keep::Bool=false)
  2. 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

  1. julia> open("my_file.txt", "w") do io
  2. write(io, "JuliaLang is a GitHub organization.\nIt has many members.\n");
  3. end
  4. 57
  5. julia> readlines("my_file.txt")
  6. 2-element Array{String,1}:
  7. "JuliaLang is a GitHub organization."
  8. "It has many members."
  9. julia> readlines("my_file.txt", keep=true)
  10. 2-element Array{String,1}:
  11. "JuliaLang is a GitHub organization.\n"
  12. "It has many members.\n"
  13. julia> rm("my_file.txt")

source

Base.eachline — Function.

  1. eachline(io::IO=stdin; keep::Bool=false)
  2. 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

  1. julia> open("my_file.txt", "w") do io
  2. write(io, "JuliaLang is a GitHub organization.\n It has many members.\n");
  3. end;
  4. julia> for line in eachline("my_file.txt")
  5. print(line)
  6. end
  7. JuliaLang is a GitHub organization. It has many members.
  8. julia> rm("my_file.txt");

source

Base.displaysize — Function.

  1. 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

  1. julia> withenv("LINES" => 30, "COLUMNS" => 100) do
  2. displaysize()
  3. end
  4. (30, 100)

To get your TTY size,

  1. julia> displaysize(stdout)
  2. (34, 147)

source

多媒体 I/O

就像文本输出用 print 实现,用户自定义类型可以通过重载 show 来指定其文本化表示, Julia 提供了一个应用于富多媒体输出的标准化机制 (例如图片、格式化文本、甚至音频和视频),由以下三部分组成:

  • 函数 display(x) 来请求一个 Julia 对象 x 最丰富的多媒体展示,并以纯文本作为后备模式。
  • 重载 show 允许指定用户自定义类型的任意多媒体表现形式(以标准MIME类型为键值)。
  • 支持多媒体显示后端可以被注册,通过子类化通用的 AbstractDisplay 类型 并通过 pushdisplay 将其压进显示后端的栈中。基础 Julia 运行环境只提供纯文本显示, 但是更富的显示可以通过加载外部模块或者使用图形化 Julia 环境 (比如基于 IPython 的 IJulia notebook)来实现。

Base.Multimedia.display — Function.

  1. display(x)
  2. display(d::AbstractDisplay, x)
  3. display(mime, x)
  4. display(d::AbstractDisplay, mime, x)

AbstractDisplay x using the topmost applicable display in the display stack, typically using the richest supported multimedia output for x, with plain-text stdout output as a fallback. The display(d, x) variant attempts to display x on the given display d only, throwing a MethodError if d cannot display objects of this type.

In general, you cannot assume that display output goes to stdout (unlike print(x) or show(x)). For example, display(x) may open up a separate window with an image. display(x) means "show x in the best way you can for the current output device(s)." If you want REPL-like text output that is guaranteed to go to stdout, use show(stdout, "text/plain", x) instead.

There are also two variants with a mime argument (a MIME type string, such as "image/png"), which attempt to display x using the requested MIME type only, throwing a MethodError if this type is not supported by either the display(s) or by x. With these variants, one can also supply the "raw" data in the requested MIME type by passing x::AbstractString (for MIME types with text-based storage, such as text/html or application/postscript) or x::Vector{UInt8} (for binary MIME types).

source

Base.Multimedia.redisplay — Function.

  1. redisplay(x)
  2. redisplay(d::AbstractDisplay, x)
  3. redisplay(mime, x)
  4. redisplay(d::AbstractDisplay, mime, x)

By default, the redisplay functions simply call display. However, some display backends may override redisplay to modify an existing display of x (if any). Using redisplay is also a hint to the backend that x may be redisplayed several times, and the backend may choose to defer the display until (for example) the next interactive prompt.

source

Base.Multimedia.displayable — Function.

  1. displayable(mime) -> Bool
  2. displayable(d::AbstractDisplay, mime) -> Bool

Returns a boolean value indicating whether the given mime type (string) is displayable by any of the displays in the current display stack, or specifically by the display d in the second variant.

source

Base.show — Method.

  1. show(io, mime, x)

The display functions ultimately call show in order to write an object x as a given mime type to a given I/O stream io (usually a memory buffer), if possible. In order to provide a rich multimedia representation of a user-defined type T, it is only necessary to define a new show method for T, via: show(io, ::MIME"mime", x::T) = …, where mime is a MIME-type string and the function body calls write (or similar) to write that representation of x to io. (Note that the MIME"" notation only supports literal strings; to construct MIME types in a more flexible manner use MIME{Symbol("")}.)

For example, if you define a MyImage type and know how to write it to a PNG file, you could define a function show(io, ::MIME"image/png", x::MyImage) = … to allow your images to be displayed on any PNG-capable AbstractDisplay (such as IJulia). As usual, be sure to import Base.show in order to add new methods to the built-in Julia function show.

The default MIME type is MIME"text/plain". There is a fallback definition for text/plain output that calls show with 2 arguments. Therefore, this case should be handled by defining a 2-argument show(io::IO, x::MyType) method.

Technically, the MIME"mime" macro defines a singleton type for the given mime string, which allows us to exploit Julia's dispatch mechanisms in determining how to display objects of any given type.

The first argument to show can be an IOContext specifying output format properties. See IOContext for details.

source

Base.Multimedia.showable — Function.

  1. showable(mime, x)

Returns a boolean value indicating whether or not the object x can be written as the given mime type.

(By default, this is determined automatically by the existence of the corresponding show method for typeof(x). Some types provide custom showable methods; for example, if the available MIME formats depend on the value of x.)

Examples

  1. julia> showable(MIME("text/plain"), rand(5))
  2. true
  3. julia> showable("img/png", rand(5))
  4. false

source

Base.repr — Method.

  1. repr(mime, x; context=nothing)

Returns an AbstractString or Vector{UInt8} containing the representation of x in the requested mime type, as written by show(io, mime, x) (throwing a MethodError if no appropriate show is available). An AbstractString is returned for MIME types with textual representations (such as "text/html" or "application/postscript"), whereas binary data is returned as Vector{UInt8}. (The function istextmime(mime) returns whether or not Julia treats a given mime type as text.)

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 show.

As a special case, if x is an AbstractString (for textual MIME types) or a Vector{UInt8} (for binary MIME types), the repr function assumes that x is already in the requested mime format and simply returns x. This special case does not apply to the "text/plain" MIME type. This is useful so that raw data can be passed to display(m::MIME, x).

In particular, repr("text/plain", x) is typically a "pretty-printed" version of x designed for human consumption. See also repr(x) to instead return a string corresponding to show(x) that may be closer to how the value of x would be entered in Julia.

Examples

  1. julia> A = [1 2; 3 4];
  2. julia> repr("text/plain", A)
  3. "2×2 Array{Int64,2}:\n 1 2\n 3 4"

source

如上面提到的,用户可以定义新的显示后端。 例如,可以在窗口显示 PNG 图片的模块可以在 Julia 中注册这个能力, 以便为有 PNG 表示的类型调用 display(x) 时可以在模块窗口中自动显示图片。

为了定义新的显示后端,应该首先创建抽象类AbstractDisplay的子类型D

然后,对于每个可以显示在 D 上的MIME类型 (mime string), 用户应该定义一个函数 display(d::D, ::MIME"mime", x) = … 这里的 x 表示为 MIME 类型, 经常在 show(io, mime, x)repr(io, mime, x) 中被调用。 如果 x 不能被表示为 MIME 类型则 MethodError 会被抛出; 这在用户调用 showrepr 的时候是会自动执行的。

最后,用户应该定义一个函数 display(d::D, x) 来查询 showable(mime, x) 以获得 D 支持的 mime 类型并把它显示为"最好"的一个; 如果没有为 x 找到支持的 MIME 类型,就应该抛出 MethodError。 类似地,一些子类型可能希望重写 redisplay(d::D, …)。 (同样,用户也应该通过 import Base.display 去添加新的方法去 display。) 这些函数的返回值取决于实现(因为在某些情况下,返回某种类型的显示“句柄”可能很有用)。 D 的显示功能可以直接调用,但它们也可以从 display(x) 自动调用, 只需在显示后端栈中添加一个新显示即可:

Base.Multimedia.pushdisplay — Function.

  1. 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

Base.Multimedia.popdisplay — Function.

  1. popdisplay()
  2. popdisplay(d::AbstractDisplay)

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

source

Base.Multimedia.TextDisplay — Type.

  1. 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

Base.Multimedia.istextmime — Function.

  1. 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

  1. julia> istextmime(MIME("text/plain"))
  2. true
  3. julia> istextmime(MIME("img/png"))
  4. false

source

网络 I/O

Base.bytesavailable — Function.

  1. bytesavailable(io)

Return the number of bytes available for reading before a read from this stream or buffer will block.

Examples

  1. julia> io = IOBuffer("JuliaLang is a GitHub organization");
  2. julia> bytesavailable(io)
  3. 34

source

Base.ntoh — Function.

  1. ntoh(x)

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

source

Base.hton — Function.

  1. hton(x)

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

source

Base.ltoh — Function.

  1. ltoh(x)

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

source

Base.htol — Function.

  1. htol(x)

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

source

Base.ENDIAN_BOM — Constant.

  1. 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