Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 755
John Horton Avatar asked Jan 31 '12 05:01

John Horton


1 Answers

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...

like image 180
Tom Regner Avatar answered Oct 24 '22 02:10

Tom Regner