简体   繁体   English

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

[英]Emacs Org Mode: Executing simple python code

How can I execute very simple Python-Code in Emacs' Org Mode? 如何在Emacs的Org模式下执行非常简单的Python代码?

The first example works fine, however I can't make it give me the result of simplest computations: 第一个例子工作正常,但我不能让它给我最简单的计算结果:

; 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

I set up Org Mode using the following lines: 我使用以下行设置组织模式:

;; 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)

There are two ways of getting the result of a source block - output and value . 获取源块的结果有两种方法 - outputvalue You mixed them up, hence the troubles. 你混淆了他们,因此麻烦。

First block is fine. 第一块很好。

To fix the second block: 要修复第二个块:

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

To fix the third block: 要修复第三个块:

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

When output mode is value you must return . 当输出模式为value您必须return Just putting it there like you did with 1+1 won't do. 就像你用1+1那样把它放在那里就不行了。 In the third one you want the result to be printed output, but your default session setting is value (mine defaults to output btw). 在第三个中,您希望结果是打印输出,但您的默认会话设置是value (我的默认值为output btw)。

And this bit about org-confirm-babel-evaluate is kind of irrelevant to the question. 关于org-confirm-babel-evaluate这一点与这个问题无关。 I just have it set to nil . 我把它设置nil

You may still face problems like blank lines cause error in function definition. 您可能仍然会遇到空行等问题导致函数定义出错。 The solution is given in original thread . 解决方案以原始线程给出。 I also posted below 我也发布在下面

(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))))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM