在 org 文件中包含代码片段

Include code snippet in org file

我想使用 org 模式写一本技术书籍。我正在寻找一种方法将现有代码从外部文件插入到 babel 代码块中,这样在导出为 pdf 时可以提供很好的格式。

例如

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

然后会给我相当于 foo.py

中第 45 行到第 50 行的以下内容
#+BEGIN_SRC python
 def times_two(x):
   y = x*2
   return y

 print times_two(5)    
#+END_SRC

有办法吗?

我认为这样的方法可行:

#+include: "./code/foo.py" :lines "45-50"

Link 到手动:http://orgmode.org/manual/Include-files.html

您可以使用 shell 脚本通过 :wrap header 打印行。例如,我在这里打印 wos.py 脚本的第 9-18 行。如果您也设置了 :exports,shell 脚本将不会导出。

#+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

如果您没有 sed,您可以编写一个 python 脚本来做同样的事情。只要记住将行号移动一位,并将结果设置为代码即可。

#+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