Movatterモバイル変換


[0]ホーム

URL:


IEx(IEx v1.18.3)

View Source

Elixir's interactive shell.

Some of the functionalities described here will not be availabledepending on your terminal. In particular, if you get a messagesaying that the smart terminal could not be run, some of thefeatures described here won't work.

Helpers

IEx provides a bunch of helpers. They can be accessed by typingh() into the shell or as a documentation for theIEx.Helpers module.

Autocomplete

To discover a module's public functions or other modules, type the module namefollowed by a dot, then press tab to trigger autocomplete. For example:

Enum.

A module may export functions that are not meant to be used directly:these functions won't be autocompleted by IEx. IEx will not autocompletefunctions annotated with@doc false,@impl true, or functions thataren't explicitly documented and where the function name is in the formof__foo__.

Autocomplete is available by default on Windows shells from Erlang/OTP 26.

Encoding and coloring

IEx expects inputs and outputs to be in UTF-8 encoding. This is thedefault for most Unix terminals but it may not be the case on Windows.If you are running on Windows and you see incorrect values printed,you may need to change the encoding of your current session by runningchcp 65001 before callingiex (or before callingiex.bat if usingPowerShell).

Similarly, ANSI coloring is enabled by default on most Unix terminals.They are also available on Windows consoles from Windows 10 and onErlang/OTP 26 or later. For earlier Erlang/OTP versions, you canexplicitly enable it for the current user in the registry by runningthe following command:

$reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1

After running the command above, you must restart your current console.

Shell history

It is possible to get shell history by passing some options that enable itin the VM. This can be done on a per-need basis when starting IEx:

$iex --erl "-kernel shell_history enabled"

If you would rather enable it on your system as a whole, you can usetheERL_AFLAGS environment variable and make sure that it is setaccordingly on your terminal/shell configuration.

On Unix-like / Bash:

$export ERL_AFLAGS="-kernel shell_history enabled"

On Windows:

$set ERL_AFLAGS "-kernel shell_history enabled"

On Windows 10 / PowerShell:

$$env:ERL_AFLAGS = "-kernel shell_history enabled"

Expressions in IEx

As an interactive shell, IEx evaluates expressions. This has someinteresting consequences that are worth discussing.

The first one is that the code is truly evaluated and not compiled.This means that any benchmarking done in the shell is going to haveskewed results. So never run any profiling nor benchmarks in the shell.

Second, IEx allows you to break an expression into many lines,since this is common in Elixir. For example:

iex(1)>"ab...(1)>c""ab\nc"

In the example above, the shell will be expecting more input until itfinds the closing quote. Sometimes it is not obvious which characterthe shell is expecting, and the user may find themselves trapped inthe state of incomplete expression with no ability to terminate it otherthan by exiting the shell.

For such cases, there is a special break-trigger (#iex:break) that whenencountered on a line by itself will force the shell to break out of anypending expression and return to its normal state:

iex(1)>["ab...(1)>c"...(1)>"...(1)>]...(1)>#iex:break** (TokenMissingError) iex:1: incomplete expression

Pasting multiline expressions into IEx

IEx evaluates its input line by line in an eager fashion. If at the end of aline the code seen so far is a complete expression, IEx will evaluate it atthat point.

iex(1)>[1,[2],3][1,[2],3]

To prevent this behavior breaking valid code where the subsequent linebegins with a binary operator, such as|>/2 or++/2 , IEx automaticallytreats such lines as if they were prepended withIEx.Helpers.v/0, whichreturns the value of the previous expression, if available.

iex(1)>[1,[2],3][1,[2],3]iex(2)>|>List.flatten()[1,2,3]

The above is equivalent to:

iex(1)>[1,[2],3][1,[2],3]iex(2)>v()|>List.flatten()[1,2,3]

If there are no previous expressions in the history, the pipe operator willfail:

iex(1)>|>List.flatten()** (RuntimeError) v(-1) is out of bounds

If the previous expression was a match operation, the pipe operator will alsofail, to prevent an unsolicited break of the match:

iex(1)>x=42iex(2)>|>IO.puts()** (SyntaxError) iex:2:1: pipe shorthand is not allowed immediately after a match expression in IEx. To make it work, surround the whole pipeline with parentheses ('|>')    |2||>IO.puts()|^

Note, however, the above does not work for+/2 and-/2, as theyare ambiguous with the unary+/1 and-/1:

iex(1)>11iex(2)>+22

The BREAK menu

Inside IEx, hittingCtrl+C will open up theBREAK menu. In thismenu you can quit the shell, see process and ETS tables informationand much more.

Exiting the shell

There are a few ways to quit the IEx shell:

  • via theBREAK menu (available viaCtrl+C) by typingq, pressing enter
  • by hittingCtrl+C,Ctrl+C
  • by hittingCtrl+\

If you are connected to remote shell, it remains alive after disconnection.

dbg and breakpoints

IEx integrates withKernel.dbg/2 and introduces a backend thatcan pause code execution. To enable it, you must pass--dbg pry:

$iex --dbg pry

For example, take the following function:

defmy_fun(arg1,arg2)dodbg(arg1+arg2)...implementation...end

When the code is executed withiex (most often by callingiex --dbg pry -S mix), it will ask you permission to use "pry".If you agree, it will start an IEx shell in the context of the functionabove, with access to its variables, imports, and aliases. However,you can only access existing values, it is not possible to accessprivate functions nor change the execution itself (hence the name"pry").

When using|> dbg() at the end of a pipeline, you can pry eachstep of the pipeline. You can typen whenever you want to jumpinto the next pipe. Typecontinue when you want to execute allof the steps but stay within the pried process. Typerespawn whenyou want to leave the pried process and start a new shell.

Alternatively, you can start a pry session directly, withoutdbg/2by callingIEx.pry/0.

IEx also allows you to set breakpoints to start pry sessionson a given module, function, and arity you have no control ofviaIEx.break!/4. Similar to pipelines indbg(),IEx.break!/4allows you to debug a function line by line and access its variables.However, breakpoints do not contain information about imports andaliases from the source code.

When usingdbg or breakpoints with tests, remember to pass the--trace tomix test to avoid running into timeouts:

$iex -S mix test --trace$iex -S mix test path/to/file:line --trace

The User switch command

Besides theBREAK menu, one can typeCtrl+G to get to theUser switch command menu. When reached, you can typeh toget more information.

In this menu, developers are able to start new shells andalternate between them. Let's give it a try:

Userswitchcommand-->siex-->c

The command above will start a new shell and connect to it.Create a new variable calledhello and assign some value to it:

hello=:world

Now, let's roll back to the first shell:

Userswitchcommand-->c1

Now, try to access thehello variable again:

hello** (CompileError) undefined variable "hello"

The command above fails because we have switched shells.Since shells are isolated from each other, you can't access thevariables defined in one shell from the other one.

TheUser switch command can also be used to terminate an existingsession, for example when the evaluator gets stuck in an infiniteloop or when you are stuck typing an expression:

Userswitchcommand-->i-->c

TheUser switch command menu also allows developers to connect toremote shells using ther command. A topic which we will discuss next.

Remote shells

IEx allows you to connect to another node in two fashions.First of all, we can only connect to a shell if we give namesboth to the current shell and the shell we want to connect to.

Let's give it a try. First, start a new shell:

$iex --sname fooiex(foo@HOST)1>

The string between the parentheses in the prompt is the nameof your node. We can retrieve it by calling thenode/0function:

iex(foo@HOST)1>node():"foo@HOST"iex(foo@HOST)2>Node.alive?()true

For fun, let's define a simple module in this shell too:

iex(foo@HOST)3>defmoduleHellodo...(foo@HOST)3>defworld,do:"it works!"...(foo@HOST)3>end

Now, let's start another shell, giving it a name as well:

$iex --sname bariex(bar@HOST)1>

If we try to dispatch toHello.world/0, it won't be availableas it was defined only in the other shell:

iex(bar@HOST)1>Hello.world()** (UndefinedFunctionError) undefined function Hello.world/0

However, we can connect to the other shell remotely. Open uptheUser switch command prompt (Ctrl+G) and type:

Userswitchcommand-->r'foo@HOST''Elixir.IEx'-->c

Now we are connected into the remote node, as the prompt shows us,and we can access the information and modules defined over there:

iex(foo@HOST)1>Hello.world()"it works!"

In fact, connecting to remote shells is so common that we providea shortcut via the command line as well:

$iex --sname baz --remsh foo@HOST

Where "remsh" means "remote shell". In general, Elixir supports:

  • remsh from an Elixir node to an Elixir node
  • remsh from a plain Erlang node to an Elixir node (through the ^G menu)
  • remsh from an Elixir node to a plain Erlang node (and get anerl shell there)

Connecting an Elixir shell to a remote node without Elixir isnot supported.

The .iex.exs file

When starting, IEx looks for a configured path, then for a local.iex.exs file(located in the current working directory), then for a global.iex.exs filelocated inside the directory pointed by theIEX_HOME environment variable(which defaults to~) and loads the first one it finds (if any).

The code in the chosen.iex.exs file is evaluated line by line in the shell'scontext, as if each line were being typed in the shell. For instance, any modulesthat are loaded or variables that are bound in the.iex.exs file will be availablein the shell after it has booted.

Take the following.iex.exs file:

# Load another ".iex.exs" fileimport_file("~/.iex.exs")# Import some module from lib that may not yet have been definedimport_if_available(MyApp.Mod)# Print something before the shell startsIO.puts("hello world")# Bind a variable that'll be accessible in the shellvalue=13

Running IEx in the directory where the above.iex.exs file is locatedresults in:

$iexErlang/OTP 24 [...]hello worldInteractive Elixir - press Ctrl+C to exit (type h() ENTER for help)iex(1)> value13

It is possible to load another file by configuring theiex application'sdot_iexvalue (config :iex, dot_iex: "PATH" orIEx.configure(dot_iex: "PATH"))or supplying the--dot-iex option to IEx. Seeiex --help.

In case of remote nodes, the location of the.iex.exs files are takenrelative to the user that started the application, not to the user thatis connecting to the node in case of remote IEx connections.

Configuring the shell

There are a number of customization options provided by IEx. Take a lookat the docs for theIEx.configure/1 function by typingh IEx.configure/1.

Those options can be configured in your project configuration file or globallyby callingIEx.configure/1 from your~/.iex.exs file. For example:

# .iex.exsIEx.configure(inspect:[limit:3])

Now run the shell:

$iexErlang/OTP 24 [...]Interactive Elixir - press Ctrl+C to exit (type h() ENTER for help)iex(1)> [1, 2, 3, 4, 5][1, 2, 3, ...]

Summary

Functions

Macro-based shortcut forIEx.break!/4.

Sets up a breakpoint inmodule,function andarity withthe given number ofstops.

Returnsstring escaped using the specifiedcolor.

Returns IEx configuration.

Configures IEx.

Returns the options used for inspecting.

Pries into the process environment.

Returnstrue if IEx was started,false otherwise.

Returns the IEx width for printing.

Functions

break!(ast, stops \\ 1)

(since 1.5.0)(macro)

Macro-based shortcut forIEx.break!/4.

break!(module, function, arity, stops \\ 1)

(since 1.5.0)
@spec break!(module(),atom(),arity(),non_neg_integer()) ::IEx.Pry.id()

Sets up a breakpoint inmodule,function andarity withthe given number ofstops.

This function will instrument the given module and load a newversion in memory with line by line breakpoints at the givenfunction and arity. If the module is recompiled, all breakpointsare lost.

When a breakpoint is reached, IEx will ask if you want toprythe given function and arity. In other words, this works similartoIEx.pry/0 as the running process becomes the evaluator ofIEx commands and is temporarily changed to have a custom groupleader. However, differently fromIEx.pry/0, aliases and importsfrom the source code won't be available in the shell.

IEx helpers includes many conveniences related to breakpoints.Below they are listed with the full module, such asIEx.Helpers.breaks/0,but remember it can be called directly asbreaks() inside IEx.They are:

By default, the number of stops in a breakpoint is 1. Any follow-upcall won't stop the code execution unless another breakpoint is set.

Alternatively, the number of stops can be increased by passing thestopsargument.IEx.Helpers.reset_break/1 andIEx.Helpers.reset_break/3can be used to reset the number back to zero. Note the module remains"instrumented" even after all stops on all breakpoints are consumed.You can remove the instrumentation in a given module by callingIEx.Helpers.remove_breaks/1 and on all modules by callingIEx.Helpers.remove_breaks/0.

Within a breakpoint, you can calln to jump to the next line.To exit a breakpoint, you can either invokecontinue, which willblock the shell until the next breakpoint is found or the processterminates, or invokerespawn, which starts a new IEx shell,freeing up the pried one.

Examples

The examples below will usebreak!, assuming that you are settinga breakpoint directly from your IEx shell. But you can set up a breakfrom anywhere by using the fully qualified nameIEx.break!.

The following sets up a breakpoint onURI.parse/1:

break!URI,:parse,1

This call will setup a breakpoint that stops once.To set a breakpoint that will stop 10 times:

break!URI,:parse,1,10

IEx.break!/2 is a convenience macro that allows breakpointsto be given in theMod.fun/arity format:

break!URI.parse/1

Or to set a breakpoint that will stop 10 times:

break!URI.parse/1,10

This function returns the breakpoint ID and will raise if thereis an error setting up the breakpoint.

Patterns and guards

IEx.break!/2 allows patterns to be given, triggering thebreakpoint only in some occasions. For example, to triggerthe breakpoint only when the first argument starts with the"https" string:

break!URI.parse("https"<>_,_)

Only a single break point can be set per function. So if you callIEx.break! multiple times with different patterns, only the lastpattern is kept.

Macros

While it is possible to set breakpoint in macros, remember that macrosare generally expanded at compilation time, and therefore they may neverbe invoked during runtime. Similarly, while patterns may be given tomacros, macros receive ASTs as arguments, and not values. For example,if you try to break on a macro with the following pattern:

break!MyModule.some_macro(pid)whenpid==self()

This breakpoint will never be reached, because a macro never receivesa PID. Even if you call the macro asMyModule.some_macro(self()),the macro will receive the AST representing theself() call, and notthe PID itself.

Breaks andmix test

To useIEx.break!/4 during tests, you need to runmix insidetheiex command and pass the--trace tomix test to avoid runninginto timeouts:

$iex -S mix test --trace$iex -S mix test path/to/file:line --trace

color(color, string)

@spec color(atom(),iodata()) ::iodata()

Returnsstring escaped using the specifiedcolor.

ANSI escapes instring are not processed in any way.

configuration()

@spec configuration() ::keyword()

Returns IEx configuration.

configure(options)

@spec configure(keyword()) :: :ok

Configures IEx.

The supported options are:

  • :auto_reload
  • :alive_continuation_prompt
  • :alive_prompt
  • :colors
  • :continuation_prompt
  • :default_prompt
  • :dot_iex
  • :history_size
  • :inspect
  • :parser
  • :width

They are discussed individually in the sections below.

Colors

A keyword list that encapsulates all color settings used by theshell. See documentation for theIO.ANSI module for the list ofsupported colors and attributes.

List of supported keys in the keyword list:

  • :enabled - boolean value that allows for switching the coloring on and off
  • :eval_result - color for an expression's resulting value
  • :eval_info - ... various informational messages
  • :eval_error - ... error messages
  • :eval_interrupt - ... interrupt messages
  • :stack_info - ... the stacktrace color
  • :blame_diff - ... when blaming source with no match
  • :ls_directory - ... for directory entries (ls helper)
  • :ls_device - ... device entries (ls helper)

When printing documentation, IEx will convert the Markdowndocumentation to ANSI as well. Colors for this can be configuredvia:

  • :doc_code - the attributes for code blocks (cyan, bright)
  • :doc_inline_code - inline code (cyan)
  • :doc_headings - h1 and h2 (yellow, bright)
  • :doc_title - the overall heading for the output (reverse, yellow, bright)
  • :doc_bold - (bright)
  • :doc_underline - (underline)

IEx will also color inspected expressions using the:syntax_colorsoption. Such can be disabled with:

IEx.configure(colors:[syntax_colors:false])

You can also configure the syntax colors, however, as desired.The below will format atoms in red and remove the coloring forall other data types:

IEx.configure(colors:[syntax_colors:[atom::red]])

The default values can be found inIO.ANSI.syntax_colors/0.

Inspect

A keyword list containing inspect options used by the shellwhen printing results of expression evaluation. Defaults topretty formatting with a limit of 50 entries.

To show all entries, configure the limit to:infinity:

IEx.configure(inspect:[limit::infinity])

SeeInspect.Opts for the full list of options.

Width

An integer indicating the maximum number of columns to use in output.The default value is 80 columns. The actual output width is the minimumof this number and result of:io.columns. This way you can configure IExto be your largest screen size and it should always take up the full widthof your current terminal screen.

History size

Number of expressions and their results to keep in the history.The value is an integer. When it is negative, the history is unlimited.

Prompt

This is an option determining the prompt displayed to the userwhen awaiting input.

The value is a keyword list with two possible keys representing prompt types:

  • :default_prompt - used whenNode.alive?/0 returnsfalse

  • :continuation_prompt - used whenNode.alive?/0 returnsfalseand more input is expected

  • :alive_prompt - used whenNode.alive?/0 returnstrue

  • :alive_continuation_prompt - used whenNode.alive?/0 returnstrue and more input is expected

The following values in the prompt string will be replaced appropriately:

  • %counter - the index of the history
  • %prefix - a prefix given byIEx.Server
  • %node - the name of the local node

Parser

This is an option determining the parser to use for IEx.

The parser is a "mfargs", which is a tuple with three elements:the module name, the function name, and extra arguments tobe appended. The parser receives at least three arguments, thecurrent input as a string, the parsing options as a keyword list,and the buffer as a string. It must return{:ok, expr, buffer}or{:incomplete, buffer}.

If the parser raises, the buffer is reset to an empty string.

.iex

Configure the file loaded into your IEx session when it starts.See more informationin the.iex.exs documentation.

Auto reloading

When set totrue, the:auto_reload option automatically purgesin-memory modules when they get invalidated by a concurrent compilationhappening in the Operating System.

inspect_opts()

@spec inspect_opts() ::keyword()

Returns the options used for inspecting.

pry()

(macro)

Pries into the process environment.

This function is useful for debugging a particular chunk of codewhen executed by a particular process. The process becomesthe evaluator of IEx commands and is temporarily changed tohave a custom group leader. Those values are reverted bycallingIEx.Helpers.respawn/0, which starts a new IEx shell,freeing up the pried one.

When a process is pried, all code runs inside IEx and hasaccess to all imports and aliases from the original code.However, you cannot change the execution of the code noraccess private functions of the module being pried. Modulefunctions still need to be accessed viaMod.fun(args).

See alsobreak!/4 for others ways to pry.

dbg/0 integration

By callingiex --dbg pry,iex will set this functionas the default backend fordbg/0 calls.

Examples

Let's suppose you want to investigate what is happeningwith some particular function. By invokingIEx.pry/0 fromthe function, IEx will allow you to access its binding(variables), verify its lexical information and accessthe process information. Let's see an example:

importEnum,only:[map:2]defmoduleAdderdodefadd(a,b)doc=a+brequireIEx;IEx.pry()endend

When invokingAdder.add(1, 2), you will receive a message inyour shell to pry the given environment. By allowing it,the shell will be reset and you gain access to all variablesand the lexical scope from above:

iex(1)>map([a,b,c],&IO.inspect(&1))123

Keep in mind thatIEx.pry/0 runs in the caller process,blocking the caller during the evaluation cycle. The callerprocess can be freed by callingrespawn/0, which starts anew IEx evaluation cycle, letting this one go:

iex(2)>respawn()trueInteractiveElixir-pressCtrl+Ctoexit(typeh()ENTERforhelp)

Setting variables or importing modules in IEx does notaffect the caller's environment. However, sending andreceiving messages will change the process state.

Pry and macros

When setting up Pry inside a code defined by macros, such as:

defmacro__using__(_)doquotedodefadd(a,b)doc=a+brequireIEx;IEx.pry()endendend

The variables defined insidequote won't be available duringprying due to the hygiene mechanism in quoted expressions. Thehygiene mechanism changes the variable names in quoted expressionsso they don't collide with variables defined by the users of themacros. Therefore the original names are not available.

Pry andmix test

To useIEx.pry/0 during tests, you need to runmix insidetheiex command and pass the--trace tomix test to avoid runninginto timeouts:

$iex -S mix test --trace$iex -S mix test path/to/file:line --trace

started?()

@spec started?() ::boolean()

Returnstrue if IEx was started,false otherwise.

This means the IEx application was started, but notthat its CLI interface is running.

width()

@spec width() ::pos_integer()

Returns the IEx width for printing.

Used by helpers and it has a default maximum cap of 80 chars.


[8]ページ先頭

©2009-2025 Movatter.jp