Here is a way to do it. Keep in mind it shouldn’t’ be used in actual systems, as there is a race condition here since you won’t have a stderr registered for a brief second. It should be fine for scripts like yours though:
@josevalim is there a way to turn off warnings like warning: variable "a" does not exist and is being expanded to "a()", please use parentheses to remove the ambiguity or change the variable name nofile:1
I’m trying to json encode it and then write it to stderr, but I’m only able to write it as it is without encoding. any other ideas if turning it off isn’t an option ?
The code above should hide the warnings, exactly as you asked. Without the code above:
x(1)> Code.eval_string("a")
warning: variable "a" does not exist and is being expanded to "a()", please use parentheses to remove the ambiguity or change the variable name
nofile:1
** (CompileError) nofile:1: undefined function a/0
(elixir) lib/code.ex:232: Code.eval_string/3
(stdlib) erl_eval.erl:677: :erl_eval.do_apply/6
(iex) lib/iex/evaluator.ex:249: IEx.Evaluator.handle_eval/5
(iex) lib/iex/evaluator.ex:229: IEx.Evaluator.do_eval/3
yea that is exactly why I asked again, cause I think it doesn’t answer my original question in this post which was, how do I retrieve the output of IO.puts ? as I described in this post
so basically, how do I capture the output of the following line Code.eval_string('IO.puts("test")')
I would expect the output to be in the device you registered. With a quick check of hexdocs I note StringIO.contents/1 will return a 2-tuple of input/output buffers. Have you tried that?
The results to stdio and when there’s an error (using try-rescue) then I write to stderr. after adding the lines you gave me to the .exs I don’t get anything back when there’s any type of error. normal results still work fine.
Yes, nothing is written to stderr because you have replaced the stderr device by one that captures it. You can do the reverse work and register the :standard_error back to the original process. I will leave this as an exercise.
@sadcad after reading this thread two times it seems to me that all information you need has been included here already.
One last piece of the puzzle that you might be missing still is that you can save the original device registered as :standard_error and use it later to either write to it directly or reregister it once you’re done with the eval and write the captured output after. Something like: