我想使用组织模式来撰写技术书籍。我正在寻找一种方法,可以将外部文件中的现有代码插入babel代码块,以便在导出为pdf时提供良好的格式。
例如
#+BEGIN_SRC python "./code/foo.py"
# insert_line (45,50)
#+END_SRC
Run Code Online (Sandbox Code Playgroud)
然后会给我等价于行45到50的以下内容 foo.py
#+BEGIN_SRC python
def times_two(x):
y = x*2
return y
print times_two(5)
#+END_SRC
Run Code Online (Sandbox Code Playgroud)
反正有这样做吗?
我认为这样的事情可以工作:
#+include: "./code/foo.py" :lines "45-50"
Run Code Online (Sandbox Code Playgroud)
手册链接:http : //orgmode.org/manual/Include-files.html
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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)