寻找 运行 长生不老药代码的更好方法

Looking for better way to run elixir code

elixir 的新手,我只找到了 2 种 运行 代码的方法。想知道有没有更好的方法:

  1. 通过调用 Module_name.function_name() 打开模块内的交互式 shell 和 运行 一个或多个函数 运行 函数

  2. 如果我想 运行 整个模块然后我打开交互式 shell 并且必须将模块中的所有代码粘贴到 shell 然后点击enter

我相信这很明显,但我找不到任何令人满意的答案。刚刚尝试使用此模块的选项 #2,它 return 在它应该 return 评论列表时编辑了它。谢谢。

defmodule KgbScrape do
  use HTTPoison.Base
  @endpoint "https://www.dealerrater.com/dealer/McKaig-Chevrolet-Buick-A-Dealer-For-The-People-dealer-reviews-23685/page"

  def build_urls() do
    page_num = ["1","2","3","4","5"]
    tail_url = ["/?filter=#link"]
    for page <- page_num, tail <- tail_url do
      urls_list = @endpoint <> page <> tail
    end
  end
  def fetch_pages(url) do
    url
    |> HTTPoison.get()
    |> response()
  end

  def process_pages(urls_list) when is_list(urls_list) do
    resp =
      urls_list
      |> Task.async_stream(fn url -> fetch_pages(url) end)
      |> Enum.map(fn {_, resp} -> resp end)

    Enum.map(resp, fn r ->
      r
      |> Floki.parse_document!()
      |> Floki.find(".review-entry")
      |> Map.new(fn entry ->
        [{"div", _, [date]}] = Floki.find(entry, "div.italic")
        [{"p", _, [content]}]  = Floki.find(entry, "p.review-content")
        {date, content}
      end)
    end)
  end

  def response({:ok, %{body: {:ok, %{"error" => error}}}}) do
    {:error, error}
  end
  def response({:ok, %{body: body}}), do: body
  def response({:error, error}), do: {:error, error}
end

结果是:

warning: redefining module KgbScrape (current version loaded from _build/dev/lib/kgbScrapeApp/ebin/Elixir.KgbScrape.beam)
  iex:7

warning: variable "urls_list" is unused (if the variable is not meant to be used, prefix it with an underscore)
  iex:15: KgbScrape.build_urls/0

{:module, KgbScrape,
 <<70, 79, 82, 49, 0, 0, 68, 252, 66, 69, 65, 77, 65, 116, 85, 56, 0, 0,
   5, 107, 0, 0, 0, 103, 16, 69, 108, 105, 120, 105, 114, 46, 75, 103,
   98, 83, 99, 114, 97, 112, 101, 8, 95, 95, 105, 110, 102, ...>>,
 {:response, 1}}

我没用过Elixir,但是根据getting started documentation,可以使用elixir命令:

After getting familiar with the basics of the language you may want to try writing simple programs. This can be accomplished by putting the following Elixir code into a file:

IO.puts("Hello world from Elixir")

Save it as simple.exs and execute it with elixir:

$ elixir simple.exs
Hello world from Elixir

创建一个mix project并按照文档中的描述使用iex -S mix来加载项目中的所有模块。

您看到的结果是模块编译的结果。要使用该模块,必须显式调用一个函数,例如 KgbScrape.process_pages(["url1", "url2, ...]).

另外,可以创建一个 escript mix escript.build 和 运行 生成的可执行文件。