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(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;

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

8. julia> rm("myfile.txt")

source

1. open(filename::AbstractString; lock = true, keywords...) -> IOStream

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

Keyword Description Default
read open for reading !write
write open for writing truncate | append
create create if non-existent !read & write | truncate | append
truncate truncate to zero size !read & write
append seek to end false

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

The lock keyword argument controls whether operations will be locked for safe multi-threaded access.

Julia 1.5

The lock argument is available as of Julia 1.5.

source

1. open(filename::AbstractString, [mode::AbstractString]; lock = true) -> 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:

Mode Description Keywords
r read none
w write, create, truncate write = true
a write, create, append append = true
r+ read, write read = true, write = true
w+ read, write, create, truncate truncate = true, read = true
a+ read, write, create, append append = true, read = true

The lock keyword argument controls whether operations will be locked for safe multi-threaded access.

Examples

1. julia> io = open("myfile.txt", "w");

3. julia> write(io, "Hello world!");

5. julia> close(io);

7. julia> io = open("myfile.txt", "r");

9. julia> read(io, String)
10. "Hello world!"

12. julia> write(io, "This file is read only")
13. ERROR: ArgumentError: write failed, IOStream is not writeable
14. [...]

16. julia> close(io)

18. julia> io = open("myfile.txt", "a");

20. julia> write(io, "This stream is not read only")
21. 28

23. julia> close(io)

25. julia> rm("myfile.txt")

Julia 1.5

The lock argument is available as of Julia 1.5.

source

1. open(fd::OS_HANDLE) -> IO

Take a raw file descriptor wrap it in a Julia-aware IO type, and take ownership of the fd handle. Call open(Libc.dup(fd)) to avoid the ownership capture of the original handle.

Warning

Do not call this on a handle that’s already owned by some other part of the system.

source

1. open(command, mode::AbstractString, stdio=devnull)

Run command asynchronously. Like open(command, stdio; read, write) except specifying the read and write flags via a mode string instead of keyword arguments. Possible mode strings are:

Mode Description Keywords
r read none
w write write = true
r+ read, write read = true, write = true
w+ read, write read = true, write = true

source

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

Start running command asynchronously, and return a process::IO object. If read is true, then reads from the process come from the process’s standard output and stdio optionally specifies the process’s standard input stream. If write is true, then writes go to the process’s standard input and stdio optionally specifies the process’s standard output stream. The process’s standard error stream is connected to the current global stderr.

source

1. open(f::Function, command, args...; kwargs...)

Similar to open(command, args...; kwargs...), but calls f(stream) on the resulting process stream, then closes the input stream and waits for the process to complete. Return the value returned by f on success. Throw an error if the process failed, or if the process attempts to print anything to stdout.

source

Base.IOStream — Type

1. IOStream

A buffered IO stream wrapping an OS file descriptor. Mostly used to represent files returned by open.

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();

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

6. julia> String(take!(io))
7. "JuliaLang is a GitHub organization. It has many members."

9. julia> io = IOBuffer(b"JuliaLang is a GitHub organization.")
10. IOBuffer(data=UInt8[...], readable=true, writable=false, seekable=true, append=false, size=35, maxsize=Inf, ptr=1, mark=-1)

12. julia> read(io, String)
13. "JuliaLang is a GitHub organization."

15. julia> write(io, "This isn't writable.")
16. ERROR: ArgumentError: ensureroom failed, IOBuffer is not writeable

18. julia> io = IOBuffer(UInt8[], read=true, write=true, maxsize=34)
19. IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=34, ptr=1, mark=-1)

21. julia> write(io, "JuliaLang is a GitHub organization.")
22. 34

24. julia> String(take!(io))
25. "JuliaLang is a GitHub organization"

27. julia> length(read(IOBuffer(b"data", read=true, truncate=false)))
28. 4

30. julia> length(read(IOBuffer(b"data", read=true, truncate=true)))
31. 0

source

1. IOBuffer(string::String)

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

Examples

1. julia> io = IOBuffer("Haho");

3. julia> String(take!(io))
4. "Haho"

6. julia> String(take!(io))
7. "Haho"

source

Base.take! — Method

1. take!(b::IOBuffer)

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

Examples

1. julia> io = IOBuffer();

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

6. julia> String(take!(io))
7. "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).

The endianness of the written value depends on the endianness of the host system. Convert to/from a fixed endianness when writing/reading (e.g. using htol and ltoh) to get results that are consistent across platforms.

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

Consistent serialization:

1. julia> fname = tempname(); # random temporary filename

3. julia> open(fname,"w") do f
4. # Make sure we write 64bit integer in little-endian byte order
5. write(f,htol(Int64(42)))
6. end
7. 8

9. julia> open(fname,"r") do f
10. # Convert back to host byte order and host integer type
11. Int(ltoh(read(f,Int64)))
12. end
13. 42

Merging write calls:

1. julia> io = IOBuffer();

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

6. julia> String(take!(io))
7. "JuliaLang is a GitHub organization. It has many members."

9. julia> write(io, "Sometimes those members") + write(io, " write documentation.")
10. 44

12. julia> String(take!(io))
13. "Sometimes those members write documentation."

User-defined plain-data types without write methods can be written when wrapped in a Ref:

1. julia> struct MyStruct; x::Float64; end

3. julia> io = IOBuffer()
4. IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=0, maxsize=Inf, ptr=1, mark=-1)

6. julia> write(io, Ref(MyStruct(42.0)))
7. 8

9. julia> seekstart(io); read!(io, Ref(MyStruct(NaN)))
10. Base.RefValue{MyStruct}(MyStruct(42.0))

source

Base.read — Function

1. read(io::IO, T)

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

Note that Julia does not convert the endianness for you. Use ntoh or ltoh for this purpose.

1. read(io::IO, String)

Read the entirety of io, as a String (see also readchomp).

Examples

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

3. julia> read(io, Char)
4. 'J': ASCII/Unicode U+004A (category Lu: Letter, uppercase)

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

8. julia> read(io, String)
9. "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::AbstractArray)
2. read!(filename::AbstractString, array::AbstractArray)

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.

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.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.readeach — Function

1. readeach(io::IO, T)

Return an iterable object yielding read(io, T).

See also skipchars, eachline, readuntil.

Julia 1.6

readeach requires Julia 1.6 or later.

Examples

1. julia> io = IOBuffer("JuliaLang is a GitHub organization.\n It has many members.\n");

3. julia> for c in readeach(io, Char)
4. c == '\n' && break
5. print(c)
6. end
7. JuliaLang is a GitHub organization.

source

Base.peek — Function

1. peek(stream[, T=UInt8])

Read and return a value of type T from a stream without advancing the current position in the stream.

Examples

1. julia> b = IOBuffer("julia");

3. julia> peek(b)
4. 0x6a

6. julia> position(b)
7. 0

9. julia> peek(b, Char)
10. 'j': ASCII/Unicode U+006A (category Ll: Letter, lowercase)

Julia 1.5

The method which accepts a type requires Julia 1.5 or later.

source

Base.position — Function

1. position(s)

Get the current position of a stream.

Examples

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

3. julia> seek(io, 5);

5. julia> position(io)
6. 5

8. julia> skip(io, 10);

10. julia> position(io)
11. 15

13. julia> seekend(io);

15. julia> position(io)
16. 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.");

3. julia> seek(io, 5);

5. julia> read(io, Char)
6. '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.");

3. julia> seek(io, 5);

5. julia> read(io, Char)
6. 'L': ASCII/Unicode U+004C (category Lu: Letter, uppercase)

8. julia> seekstart(io);

10. julia> read(io, Char)
11. '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.");

3. julia> seek(io, 5);

5. julia> skip(io, 10);

7. julia> read(io, Char)
8. '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");

3. julia> isreadonly(io)
4. true

6. julia> io = IOBuffer();

8. julia> isreadonly(io)
9. 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

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

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

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

12. 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+");

3. julia> isopen(io)
4. true

6. julia> close(io)

8. julia> isopen(io)
9. false

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_stdio — Function

1. redirect_stdio(;stdin=stdin, stderr=stderr, stdout=stdout)

Redirect a subset of the streams stdin, stderr, stdout. Each argument must be an IOStream, TTY, Pipe, socket, or devnull.

Julia 1.7

redirect_stdio requires Julia 1.7 or later.

source

1. redirect_stdio(f; stdin=nothing, stderr=nothing, stdout=nothing)

Redirect a subset of the streams stdin, stderr, stdout, call f() and restore each stream.

Possible values for each stream are:

  • nothing indicating the stream should not be redirected.
  • path::AbstractString redirecting the stream to the file at path.
  • io an IOStream, TTY, Pipe, socket, or devnull.

Examples

1. julia> redirect_stdio(stdout="stdout.txt", stderr="stderr.txt") do
2. print("hello stdout")
3. print(stderr, "hello stderr")
4. end

6. julia> read("stdout.txt", String)
7. "hello stdout"

9. julia> read("stderr.txt", String)
10. "hello stderr"

Edge cases

It is possible to pass the same argument to stdout and stderr:

1. julia> redirect_stdio(stdout="log.txt", stderr="log.txt", stdin=devnull) do
2. ...
3. end

However it is not supported to pass two distinct descriptors of the same file.

1. julia> io1 = open("same/path", "w")

3. julia> io2 = open("same/path", "w")

5. julia> redirect_stdio(f, stdout=io1, stderr=io2) # not suppored

Also the stdin argument may not be the same descriptor as stdout or stderr.

1. julia> io = open(...)

3. julia> redirect_stdio(f, stdout=io, stdin=io) # not supported

Julia 1.7

redirect_stdio requires Julia 1.7 or later.

source

Base.redirect_stdout — Function

1. redirect_stdout([stream]) -> stream

Create a pipe to which all C and Julia level stdout output will be redirected. Return a stream representing the pipe ends. Data written to stdout may now be read from the rd end of the pipe.

Note

stream must be a compatible objects, such as an IOStream, TTY, Pipe, socket, or devnull.

See also redirect_stdio.

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.

source

Base.redirect_stderr — Function

1. redirect_stderr([stream]) -> stream

Like redirect_stdout, but for stderr.

Note

stream must be a compatible objects, such as an IOStream, TTY, Pipe, socket, or devnull.

See also redirect_stdio.

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.

source

Base.redirect_stdin — Function

1. redirect_stdin([stream]) -> stream

Like redirect_stdout, but for stdin. Note that the direction of the stream is reversed.

Note

stream must be a compatible objects, such as an IOStream, TTY, Pipe, socket, or devnull.

See also redirect_stdio.

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.

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;

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

8. 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();

3. julia> write(io, "JuliaLang is a GitHub organization.")
4. 35

6. julia> truncate(io, 15)
7. IOBuffer(data=UInt8[...], readable=true, writable=true, seekable=true, append=false, size=15, maxsize=Inf, ptr=16, mark=-1)

9. julia> String(take!(io))
10. "JuliaLang is a "

12. julia> io = IOBuffer();

14. julia> write(io, "JuliaLang is a GitHub organization.");

16. julia> truncate(io, 40);

18. julia> String(take!(io))
19. "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)

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

7. julia> String(readavailable(buf))
8. "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.

To count lines of a String, countlines(IOBuffer(str)) can be used.

Examples

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

3. julia> countlines(io)
4. 1

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

8. julia> countlines(io)
9. 1

11. julia> eof(io) # counting lines moves the file pointer
12. true

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

16. julia> countlines(io, eol = '.')
17. 1

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 available buffered data from a stream. Actual I/O is performed only if no data has already been buffered. The result is a Vector{UInt8}.

Warning

The amount of data returned is implementation-dependent; for example it can depend on the internal choice of buffer size. Other functions such as read should generally be used instead.

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 key

The following properties are in common use:

  • :compact: Boolean specifying that values should be printed more compactly, e.g. that numbers should be printed with fewer digits. This is set when printing array elements. :compact output should not contain line breaks.
  • :limit: Boolean specifying that containers should be truncated, e.g. showing … in place of most elements.
  • :displaysize: 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();

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

5. julia> String(take!(io))
6. "\e[31mstring\e[39m"

8. julia> printstyled(io, "string", color=:red)

10. julia> String(take!(io))
11. "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)

10. julia> f(stdout)
11. loooooong
12. julia> f(IOContext(stdout, :short => true))
13. 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([io::IO = stdout], x)

Write a text representation of a value x to the output stream io. New types T should overload show(io::IO, x::T). The representation used by show generally includes Julia-specific formatting and type information, and should be parseable Julia code when possible.

repr returns the output of show as a string.

To customize human-readable text output for objects of type T, define show(io::IO, ::MIME"text/plain", ::T) instead. Checking the :compact IOContext property of io in such methods is recommended, since some containers show their elements by calling this method with :compact => true.

See also print, which writes un-decorated representations.

Examples

1. julia> show("Hello World!")
2. "Hello World!"
3. julia> print("Hello World!")
4. Hello World!

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"

4. julia> summary(zeros(2))
5. "2-element Vector{Float64}"

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. The representation used by print includes minimal formatting and tries to avoid Julia-specific details.

print falls back to calling show, so most types should just define show. Define print if your type has a separate “plain” representation. For example, show displays strings with quotes, and print displays strings without quotes.

See also println, string, printstyled.

Examples

1. julia> print("Hello World!")
2. Hello World!
3. julia> io = IOBuffer();

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

7. julia> String(take!(io))
8. "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.

See also printstyled to add colors etc.

Examples

1. julia> println("Hello, world")
2. Hello, world

4. julia> io = IOBuffer();

6. julia> println(io, "Hello", ',', " world.")

8. julia> String(take!(io))
9. "Hello, world.\n"

source

Base.printstyled — Function

1. printstyled([io], xs...; bold::Bool=false, underline::Bool=false, blink::Bool=false, reverse::Bool=false, hidden::Bool=false, color::Union{Symbol,Int}=:normal)

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

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

Keywords bold=true, underline=true, blink=true are self-explanatory. Keyword reverse=true prints with foreground and background colors exchanged, and hidden=true should be invisibe in the terminal but can still be copied. These properties can be used in any combination.

See also print, println, show.

Julia 1.7

Keywords except color and bold were added in Julia 1.7.

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

The optional keyword argument context can be set to a :key=>value pair, a tuple of :key=>value pairs, 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.

Julia 1.7

Passing a tuple to keyword context requires Julia 1.7 or later.

Examples

1. julia> sprint(show, 66.66666; context=:compact => true)
2. "66.6667"

4. julia> sprint(showerror, BoundsError([1], 100))
5. "BoundsError: attempt to access 1-element Vector{Int64} 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::String
3. end

5. julia> function Base.showerror(io::IO, err::MyException)
6. print(io, "MyException: ")
7. print(io, err.msg)
8. end

10. julia> err = MyException("test exception")
11. MyException("test exception")

13. julia> sprint(showerror, err)
14. "MyException: test exception"

16. julia> throw(MyException("test exception"))
17. 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

6. julia> x = MyStruct(1, (2,3));

8. julia> dump(x)
9. MyStruct
10. x: Int64 1
11. y: Tuple{Int64, Int64}
12. 1: Int64 2
13. 2: Int64 3

15. julia> dump(x; maxdepth = 1)
16. MyStruct
17. x: Int64 1
18. 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 (de

(本文超出站点单文档体积上限,已截断)