4

The context

In #+BEGIN_SRC code blocks whose language is cpp or sh, the tab character is used as a delimiter for cells when using the :results table header argument (see examples below)

#+begin_src cpp :results replace output table
#include <iostream>

int main() {
  std::cout << "a\ta\nbbbbb\tbbbbb" << std::endl;
  return 0;
}
#+end_src

#+RESULTS:
| a     | a     |
| bbbbb | bbbbb |
#+begin_src sh :results replace output table
printf "%s\t%s\n" "a" "a" "bbbbbb" "bbbbbb"
#+end_src

#+RESULTS:
| a      | a      |
| bbbbbb | bbbbbb |

However, this same behavior is not present in python code blocks (see below)

#+begin_src python :results replace output table
print("a\ta\nbbbbb\tbbbbb")
#+end_src

#+RESULTS:
: a a
: bbbbb bbbbb

The question

How can I make the output of python code blocks be displayed as Org tables. Isn't using those header arguments and make the output contain tab characters enough for the #+RESULTS to be formatted as an Org table?

1
  • I use jupyter-python and it formats as tables automatically. You can also do this manually with the tabulate package. I'm not sure how to do it with unchanged Org+Python. – mankoff Sep 21 '20 at 10:23
9

You can output formatted org tables by returning a list of lists as follows (notice no :results output):

#+begin_src python :results replace table
return (('a', 'a'), None, ('bbbbb', 'bbbbb'))
#+end_src

#+RESULTS:
| a     | a     |
|-------+-------|
| bbbbb | bbbbb |

a None row creates a separator line.

Here are some other examples using :results output

#+BEGIN_SRC python :results output table
print([['Number', 'Number * 10'], None, [1, 10], [2, 20]])
#+END_SRC

#+RESULTS:
| Number | Number * 10 |
|--------+-------------|
|      1 |          10 |
|      2 |          20 |
#+BEGIN_SRC python :results value table
return [['Number', 'Number * 10'], None, [1, 10], [2, 20]]
#+END_SRC

#+RESULTS:
| Number | Number * 10 |
|--------+-------------|
|      1 |          10 |
|      2 |          20 |

Note that when using :results output, a single print is included in the #+RESULTS code block.

#+BEGIN_SRC python :results output table
for i in range(5):
  print([i, i**10])
#+END_SRC

#+RESULTS:
| 0 | 0 |

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.