[已解决] 如何在 Org-mode 中运行 Python 代码并显示器其结果?

我还在研究中,如果你在我找到解决方案前找到就知道解决方案。请麻烦你 @ 我并能提供相关链接或点拨不胜感激。

问题

我在自学计算机科学,上的课程用 Python 教。我想使用 Org-mode 并执行里面所写的 Python 代码并查看其返回值?或者输出值?

希望能得到如同 iPython Notebook 一样的效果(如下图所示)。

解决方案

首先在 Emasc 配置文件中添加下面的代码

(org-babel-do-load-languages
 'org-babel-load-languages
 '((python . t)))

之后在 Emasc 中的代码块中使用 C-c C-c

  • If the cursor is on a code block, evaluate it. The variable ‘org-confirm-babel-evaluate’ can be used to control prompting before code block evaluation, by default every code block evaluation requires confirmation. Code block evaluation can be inhibited by setting ‘org-babel-no-eval-on-ctrl-c-ctrl-c’.

解决方案来自 guanghui.qu

#+BEGIN_SRC python :results output
  import sys

  print sys.version
  print sys.prefix
#+END_SRC

#+RESULTS:
: 2.7.11 (default, Dec  5 2015, 14:44:53) 
: [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.1.76)]
: /usr/local/Cellar/python/2.7.11/Frameworks/Python.framework/Versions/2.7

如果你的函数非常简单也可以直接使用 return 来输出最终的结果,这样就不需要使用 :results output 了。

资源

文本资料

视频资源

1 个赞

只需要在 python 后面添加 :results output 即可。

#+BEGIN_SRC python :results output
  import sys

  print sys.version
  print sys.prefix
#+END_SRC

#+RESULTS:
: 2.7.10 (default, Sep 23 2015, 04:34:21) 
: [GCC 4.2.1 Compatible Apple LLVM 7.0.0 (clang-700.0.72)]
: /usr/local/Cellar/python/2.7.10_2/Frameworks/Python.framework/Versions/2.7
4 个赞

如果没有加那个:results output, 返回的是最后一个语句的返回值。

2 个赞

处理代码块的运行结果由:session 与 :results 这两个header arguments共同决定

| | Non-session | session|

|:results value |最后语句的返回值| 最后语句的返回值|

|:results output |STDOUT的输出 |解释器的输出结果|

当 =:results value= 时,无论是否开启 =:session= ,results都会尽可能的以table的方式展示出来

当 =:results value= 时,代码块的内容会被包含在一个函数中,然后执行该函数. 因此对于像Python这样的语言来说,若最后语句不是return,则一定返回None

注意 =:results output= 在session与non-session时的不同

#+BEGIN_SRC python :results output print “hello” 2 print “bye” #+END_SRC

#+RESULTS: : hello : bye

#+BEGIN_SRC python :results output :session print “hello” 2 print “bye” #+END_SRC

#+RESULTS: : hello : 2 : bye

详细参见https://github.com/emacs-china/hello-emacs/blob/master/org-manual.org

2 个赞

现在用 emacs-jupyter 似乎是更好的选择了。

1 个赞