【问题标题】:Include code snippet in org file在 org 文件中包含代码片段
【发布时间】:2016-04-13 17:50:50
【问题描述】:

我想使用 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

有没有办法做到这一点?

【问题讨论】:

    标签: org-mode


    【解决方案1】:

    我认为这样的事情可能会奏效:

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

    手册链接:http://orgmode.org/manual/Include-files.html

    【讨论】:

    • 这似乎可行,但我没有得到BEGIN_SRC 所获得的良好格式。如果我在begin_src 中使用include,那么它不会获取文件,而是逐字打印include 语句。
    • @Dan,要获取格式,您需要指定src,例如,#+include: "./code/foo.py" :lines "45-50" src python -n 将标记python并添加行号。
    • @Dan 我认为这是对包含的文件进行语法突出显示的最佳解决方案,这正是我正在寻找的。谢谢。
    【解决方案2】:

    您可以使用 shell 脚本来打印带有 :wrap 标头的行。例如,这里我打印 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
    

    【讨论】:

    • 我得到了sed 的工作,但似乎无法让 python 脚本运行。它只是给了我None。我在终端中运行了相同的脚本,它工作得很好。奇怪...
    • 您可能需要 :results 输出代码。我将默认值从值更改为输出。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-12-13
    • 2021-02-19
    • 2016-04-03
    • 2017-12-22
    • 1970-01-01
    • 2011-03-15
    相关资源
    最近更新 更多