How to handle certain output from eval_string

so it’s these two simple lines:

https://hastebin.com/bonopujawa.exs

The first one executes, the second prints to stdout. the output is a and ok.
How can I print a only ?
How can I print ok only ?

In other words, how can I access them separately ?

Code.eval_string("IO.puts('a')") will print the a. When you do IO.puts(result), that is printing the :ok.

that prints both…

It does not. Do it in iex and you will see what is happening.

iex(1)> {result, _} = Code.eval_string("IO.puts('a')")
a
{:ok, []}
iex(2)> IO.puts result
ok
:ok

The {:ok, []} from the first function call is the return value of calling Code.eval_string/3. In this case, you are binding the result variable to the atom :ok.

In the second line, you are printing out the atom :ok, which gets printed as ok. And then we see :ok as the return value of the IO.puts/2 call.

1 Like

So how would I be able to write a to stderr for example ? obviously without changing the code in eval_string.

To my knowledge, you can’t. The default IO device for the IO.puts/2 function is :stdio. You would need the code written as Code.eval_string("IO.puts(:stderr, 'a')") in order to have it go to stderr.

Any other way to split them ? maybe using regex ?

What are you trying to do?

I write the result to stdout and if I get something like IO.puts() then I write it’s output to stderr.
Like this:

{result, _} = Code.eval_string(code)
if code has IO.puts() then write it to stderr end
wrtie result to stdout

I mean at a high level. This seems like a very unusual requirement, what are you trying to achieve at the big picture level?

I simply want to write in case of IO.puts() Your console output is: and otherwise I’d write Your returned result is:

That’s pretty much what I want to achieve.

Ah. You’re trying to let someone submit arbitrary Elixir code, and then describe the results. Can’t you just capture all output as was discussed in one of the other forum questions you asked? Why do you need to rewrite stderr and stdio?

BTW nothing will stop someone from writing Elixir code that undoes whatever it is you do to capture the IO. Eval allows anything.

What do you mean ? how exactly would I then be able to write as described in my post above ?
I just wanna treat each output differently, that’s why I’m choosing stderr and stdout

Sure I’m aware of that, thanks! :pray: