0

我有一个文件,其中包含:

<html>
    <h1>Hello There</h1>
    <p>
    This is an example of a pml file
    </p>
    <pml>
    def f():
        return "<h2>First PML block</h2>"
    pml = f()
    </pml>
    <p>Here is another paragraph</p>
    <pml>
    def g():
        return "<h2>Second PML block</h2>"
    pml = g()
    </pml>
    <p>This is the last paragraph.</p>
    <pml>
    def h():
        return "<h2>Third PML block</h2>"
    pml = h()
    </pml>
</html>

我正在编写一个 python 脚本,它将生成一个输出文件,该文件将 pml 块替换为块中代码的结果。我希望输出文件看起来像:

<html>
<h1>Hello There</h1>
<p>
This is an example of a pml file
</p>
<h2>First PML block</h2>
<p>Here is another paragraph</p>
<h2>Second PML block</h2>
<p>This is the last paragraph.</p>
<h2>Third PML block</h2>
</html>

这是我的脚本:

import sys

#define main

def main(argv):
    #make sure usage is proper
    if len(sys.argv) != 3:
        print 'Usage: pmlparser.py <input_file> <output_file>'
    else:
          #get the filenames
          inputfilename = sys.argv[1]
          outputfilename = sys.argv[2]
          #open the files
          with open(inputfilename,"r") as inputfile, open(outputfilename,"w") as outputfile:    
                  for line in inputfile:
                         if not "<pml>" in line:
                               outputfile.write(line)
                         else:
                               pmlfile = open("pmlcode.py","a")
                               for line in inputfile:
                                       if not "</pml>" in line:
                                              pmlfile.write(line[1:])
                                       else:
                                              #I think the problem is somewhere in here
                                              pmlfile.close()
                                              import pmlcode
                                              outputfile.write(pmlcode.pml + "\n")
                                              break         

if __name__ == "__main__":
   main(sys.argv[1:])

不幸的是,我得到以下结果:

<html>
<h1>Hello There</h1>
<p>
This is an example of a pml file
</p>
<h2>First PML block</h2>
<p>Here is another paragraph</p>
<h2>First PML block</h2>
<p>This is the last paragraph.</p>
<h2>First PML block</h2>
</html>

我正在迭代导入 pmlcode.py,并尝试将 pml 的新值写入输出文件。但是,此脚本不断将 pml 的原始值写入输出文件。

我尝试了以下测试:

一个.py:

def f():
    return 1
var = f()
def g():
    return 2
var = g()

b.py:

import a
print a.var

$> python b.py

2

我昨天刚开始学习 Python,所以如果我的问题听起来很愚蠢或者我误解了什么,我深表歉意。我很感激任何帮助!

4

1 回答 1

0

import不是您想要的工具。正如您所发现的,一旦您导入了一个模块,您总是会得到相同的模块;Python 将其缓存在内存中以提高性能。换句话说,问题在于pmlcode.py没有更新,而在于它只是在第一次import pmlcode执行时才实际读取。

既然你已经有了一个字符串,为什么要把它写到一个文件中然后再导入呢?exec直接在字符串上使用即可。

于 2013-07-10T18:22:46.293 回答