Emacs Org Mode:执行简单的python代码

时间:2013-09-03 18:12:50

标签: python emacs org-mode

如何在Emacs的组织模式中执行非常简单的Python代码?

第一个例子工作正常,但是我不能让它给我最简单的计算结果:

; works
#+begin_src python
def foo(x):
  if x>0:
    return x+10

  else:
    return x-1

return foo(50)
#+end_src

#+RESULTS:
: 60

; does not work
#+begin_src python
1+1
#+end_src

#+RESULTS:
: None

; does not work
#+begin_src python
print(1+1)
#+end_src

#+RESULTS:
: None

我使用以下行设置组织模式:

;; enable python for in-buffer evaluation
(org-babel-do-load-languages
 'org-babel-load-languages
 '((python . t)))

;; all python code be safe
(defun my-org-confirm-babel-evaluate (lang body)
(not (string= lang "python")))
(setq org-confirm-babel-evaluate 'my-org-confirm-babel-evaluate)

2 个答案:

答案 0 :(得分:13)

two ways获得 源块的结果 - outputvalue。你混淆了他们,因此麻烦。

第一块就好了。

修复第二个块:

#+begin_src python :results value
return 1+1
#+end_src

修复第三个块:

#+begin_src python :results output
print 1+1
#+end_src

当输出模式为value时,您必须return。就像你一样把它放在那里 与1+1不会。 在第三个中,您希望结果是打印输出,但是您的默认会话 设置为value(我的默认设置为output btw。)

关于org-confirm-babel-evaluate的这一点与这个问题无关。 我把它设置为nil

答案 1 :(得分:3)

您可能仍会遇到空行等问题导致功能定义出错。解决方案在original thread中给出。我也发布在下面

(setq org-babel-python-command "ipython3 --no-banner --classic --no-confirm-exit")

;; use %cpaste to paste code into ipython in org mode
(defadvice org-babel-python-evaluate-session
(around org-python-use-cpaste
        (session body &optional result-type result-params) activate)
        "Add a %cpaste and '--' to the body, so that ipython does the right thing."
(setq body (concat "%cpaste\n" body "\n--"))
ad-do-it
(if (stringp ad-return-value)
  (setq ad-return-value (replace-regexp-in-string "\\(^Pasting code; enter '--' alone on the line to stop or use Ctrl-D\.[\r\n]:*\\)" "" ad-return-value))))