I want to run a short python simulation in org-mode and use the results later on in my continuous text. Something like:

#+begin_src python
a = 5 + 5

The result of the calculation is <<value in a>>

Which should export to the following latex code

The result of the calculation is 10.
  • You need to give a name to this block (#+name: foo) and then use it like this: call_foo() instead of <<value in a>>. – wvxvw Aug 11 '15 at 20:41
  • yeah that works. It will only print the last evaluated statement, so only 5+5 will work. Plus I have to write new cell for every variable that I want to export. I'll keep looking if I find something better. – kain88 Aug 12 '15 at 20:26

If you don't mind evaluating the whole code on export every time, you can do this:

Give the code block a session and later use inline code to call the variable, as in:

#+begin_src python :session calc :exports code :results none
a = 5 + 5

The result of the calculation is src_python[:session calc]{a}

There is another way which may not be worth the hassle for small code-blocks (depending on how complex it is in the language you are working in; R gave me problems...), but where you don't have to run the code always on export (results are persistent, but updated when you re-run the code block) using Macros that are prepared within the code-block as Macro Strings. At least, calling the results is then easier in-text:

#+begin_src python :session calc :exports code :results values drawer
a = 5 + 5
b = a-1
ares = '#+MACRO: a '+ str(a)
bres = '#+MACRO: b '+ str(b)
ares + '\n' + bres

#+MACRO: a 10
#+MACRO: b 9

The result is still {{{a}}} and b is {{{b}}}
  • This actually gave me: "The result of the calculation is a". I expected 10 instad of a. Am I doing this wrong? – Kaligule Feb 15 '17 at 17:01
  • that's strange, I get 10. If you copy-paste the gray box above to a new file, does it also happen? what if you change to :results values, and add a line below a = 5 + 5, only with a, so that a will be returned in a #+RESULTS: line (it should be 10, ot a) – TNT Feb 16 '17 at 8:35
  • Not sure why it didn't work this night, It works now. Thank you. Btw I found that what I really want is to add an :results raw so the 10 is formated as raw org text. – Kaligule Feb 16 '17 at 13:38
  • Glad it works, with raw you get the result inserted, yes, but it's not so easy to integrate it in-text as you pose in your example. If your question is answered please remember to accept the answer. – TNT Feb 17 '17 at 4:04
  • Yes, the real finding was that the org manual is indeed covering this quite good. I would accept your answer if it was mine, but in this case it is up to @kain88 – Kaligule Feb 21 '17 at 20:56

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.