Make the source code from one code block the input to another code block in Emacs org-mode

扶醉桌前 提交于 2019-12-10 01:56:48

问题


I'm getting started with org-mode and there's something I'd like to do that seems like it should be possible, but I'm having trouble figuring out.

Let me describe the scenario: I have some SQL code that I want to execute on a remote server. I currently have a python script that takes SQL code as a string and does this for me. Without org-mode, my work flow would be to start with a file like so:

echo "SELECT name, grade FROM students" >> basic_query.sql 

and then I'd run:

$ python run_query.py basic_query.sql    

To do this is in the org-mode setting, I could create a code block for the SQL:

#+NAME: basic_query 
#+BEGIN_SRC SQL 
SELECT name, grade FROM students 

#+END_SRC 

And then I'd have a code block for the python calling function:

#+BEGIN_SRC python :export results
import sql_helper 
query_status = sql_helper.run_query(<<basic_query>>)  

#+END_SRC 

Which I might use to create a table, process further, plot etc. Note the << >> thing is not right, obviously---it's just an abuse of notation to indicate what I'm trying to do.


回答1:


If you have set up emacs/org-mode so that python code is enabled ((python . t) in org-babel-do-load-languages), you are almost there, I changed your example to

#+NAME: basic_query 
#+BEGIN_SRC SQL 
  SELECT name, grade FROM students 
#+END_SRC 

#+BEGIN_SRC python :export results :noweb yes :tangle yes
import sql_helper 
query = """
    <<basic_query>>
    """
query_status = sql_helper.run_query(query)  

#+END_SRC 

My python is a little rusty, but at least if I tangle this to

import sql_helper 
query = """
    SELECT name, grade FROM students 

    """
query_status = sql_helper.run_query(query)

python does no longer complain about the syntax, but about the missing module sql_helper...



来源:https://stackoverflow.com/questions/9074967/make-the-source-code-from-one-code-block-the-input-to-another-code-block-in-emac

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!