簡體   English   中英

Emacs Org Mode:執行簡單的python代碼

[英]Emacs Org Mode: Executing simple python code

如何在Emacs的Org模式下執行非常簡單的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)

獲取源塊的結果有兩種方法 - 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

您可能仍然會遇到空行等問題導致函數定義出錯。 解決方案以原始線程給出。 我也發布在下面

(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