0

The context

When evaluating the following code block, the output is not inserted in the #+RESULTS code block. This happens because of the return 1 statement.

#+begin_src cpp :results output
#include <stdexcept>
#include <iostream>

int main()
try {
  throw std::runtime_error("A runtime error ocurred");
  return 0;
}
catch(std::runtime_error& e) {
  std::cout << "runtime_error: " << e.what() << '\n';
  return 1;
}
#+end_src

#+RESULTS:

If I replace 1 with 0, then the output is indeed shown in the #+RESULTS code block

#+RESULTS:
#+begin_example
runtime_error: A runtime error ocurred
#+end_example

Additional context

Note that this behavior is also present in #+begin_src whose language is sh. Here's a minimal working example: Evaluating the following code block would result in

#+begin_src sh
f() {
  return 1
}

printf "%s" "a"
f
#+end_src

#+RESULTS:

If the return value of the f function is changed to 0, then the output of the printf is shown

#+begin_src sh
f() {
  return 0
}

printf "%s" "a"
f
#+end_src

#+RESULTS:
#+begin_example
a
#+end_example

The question

How can I make the output of the evaluated code block be inserted in its corresponding #+RESULTS code block regardless of the exit status of the evaluation?

2

Hmm, the Org documentation isn't very clear on the intended behavior here. I'm looking at the Results of Evalution page.

But the workhorse function org-babel-eval is clear in its docstring that results only come back if the command succeeds. If the command fails, stdout is not returned and instead stderr is displayed in an error buffer.

org-babel-eval doesn't provide an easy way to change this behavior, so unfortunately I think the only way to get what you want right now is to redefine the function. A change to the following code at the end of the function seems to work on my setup:

(if (or (not (numberp exit-code)) (> exit-code 0))
    (progn
      ... error processing stuff ...
      nil)  ; <-- replace nil with (buffer-string) and reevaluate the function
  (buffer-string)))))

I don't work with babel enough to have strong feelings about the code, but you might want to raise a thread on the Org mailing list about your workflow and see if other folks would prefer this change as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.