Powered by AppSignal & Oban Pro

StringIO

elixir_livebooks/string_io.livemd

StringIO

Controls an IO device process that wraps a string.

A StringIO IO device can be passed as a “device” to most of the functions in the IO module.

Examples

{:ok, pid} = StringIO.open("foo")
IO.read(pid, 2)

Function child_spec/1

Returns a specification to start this module under a supervisor.

See Supervisor.

Function close/1

Stops the IO device and returns the remaining input/output buffers.

Examples

{:ok, pid} = StringIO.open("in")
IO.write(pid, "out")
StringIO.close(pid)

Function contents/1

Returns the current input/output buffers for the given IO device.

Examples

{:ok, pid} = StringIO.open("in")
IO.write(pid, "out")
StringIO.contents(pid)

Function flush/1

Flushes the output buffer and returns its current contents.

Examples

{:ok, pid} = StringIO.open("in")
IO.write(pid, "out")
StringIO.flush(pid)
StringIO.contents(pid)

Function open/2

Creates an IO device.

string will be the initial input of the newly created device.

options_or_function can be a keyword list of options or a function.

If options are provided, the result will be {:ok, pid}, returning the IO device created. The option :capture_prompt, when set to true, causes prompts (which are specified as arguments to IO.get* functions) to be included in the device’s output.

If a function is provided, the device will be created and sent to the function. When the function returns, the device will be closed. The final result will be a tuple with :ok and the result of the function.

Examples

{:ok, pid} = StringIO.open("foo")
IO.gets(pid, ">")
StringIO.contents(pid)
{:ok, pid} = StringIO.open("foo", capture_prompt: true)
IO.gets(pid, ">")
StringIO.contents(pid)
StringIO.open("foo", fn pid ->
  input = IO.gets(pid, ">")
  IO.write(pid, "The input was #{input}")
  StringIO.contents(pid)
end)

Function open/3

Creates an IO device.

string will be the initial input of the newly created device.

The device will be created and sent to the function given. When the function returns, the device will be closed. The final result will be a tuple with :ok and the result of the function.

Options

  • :capture_prompt - if set to true, prompts (specified as arguments to IO.get* functions) are captured in the output. Defaults to false.

  • :encoding (since v1.10.0) - encoding of the IO device. Allowed values are :unicode (default) and :latin1.

Examples

StringIO.open("foo", [], fn pid ->
  input = IO.gets(pid, ">")
  IO.write(pid, "The input was #{input}")
  StringIO.contents(pid)
end)
StringIO.open("foo", [capture_prompt: true], fn pid ->
  input = IO.gets(pid, ">")
  IO.write(pid, "The input was #{input}")
  StringIO.contents(pid)
end)