Search code examples
org-mode

Include code snippet in org file


I'm wanting to use org mode to write a technical book. I'm looking for a way to insert existing code from external file into a babel code block that would give nice formatting when exporting to pdf.

For example

#+BEGIN_SRC python "./code/foo.py" 
  # insert_line (45,50)
#+END_SRC

would then give me the equivalent of the following from line 45 to 50 in foo.py

#+BEGIN_SRC python
 def times_two(x):
   y = x*2
   return y

 print times_two(5)    
#+END_SRC

Is there anyway of doing this?


Solution

  • You can use a shell script to print the lines out with a :wrap header. For example, here I print lines 9-18 of the wos.py script. The shell script won't export if you set :exports too.

    #+BEGIN_SRC sh :wrap src python :exports results
    sed -n 9,18p wos.py
    #+END_SRC
    
    #+RESULTS:
    #+BEGIN_src python
    class HTTPSudsPreprocessor(urllib2.BaseHandler):
        def __init__(self, SID):
            self.SID = SID
    
        def http_request(self, req):
            req.add_header('cookie', 'SID="'+self.SID+'"')
            return req
    
        https_request = http_request
    
    #+END_src
    

    If you don't have sed, you can write a little python script that does the same thing. Just remember to shift the line numbers by one, and to set results to code.

    #+BEGIN_SRC python :results code :exports results
    with open("wos.py") as f:
        print("".join(f.readlines()[8:17]))    
    #+END_SRC
    
    #+RESULTS:
    #+BEGIN_SRC python
    class HTTPSudsPreprocessor(urllib2.BaseHandler):
        def __init__(self, SID):
            self.SID = SID
    
        def http_request(self, req):
            req.add_header('cookie', 'SID="'+self.SID+'"')
            return req
    
        https_request = http_request
    
    #+END_SRC