我想写一个python脚本,将一些java代码添加到一个java源文件。为什么我的模式不匹配?
#!/usr/bin/env python
import sys, getopt
import re
def read_write_file(infile):
inf = open(infile, 'r')
pat = re.compile('setContentView\(R\.layout\.main\)\;')
for line in inf:
l=line.rstrip()
if (pat.match(l)):
print l
print """
// start more ad stuff
// Look up the AdView as a resource and load a request.
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// end more ad stuff
"""
sys.exit(0)
else:
print l
inf.close
def main(argv):
inputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:",["ifile="])
except getopt.GetoptError:
print 'make_main_xml.py -i <inputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print """
usage : make_main_activity.py -i <inputfile>
where <inputfile> is the main activity java file
like TwelveYearsaSlave_AdmobFree_AudiobookActivity.java
"""
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
read_write_file(inputfile)
if __name__ == "__main__":
main(sys.argv[1:])
...这里是典型的输入文件,该脚本上运行...
public static Context getAppContext() {
return context;
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
context = getApplicationContext();
setContentView(R.layout.main);
}
...实际的Java源文件是巨大的,但我只是想插入文本。 ..
// start more ad stuff
// Look up the AdView as a resource and load a request.
AdView adView = (AdView)this.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
// end more ad stuff
...右后...
setContentView(R.layout.main);
...但是当我运行脚本时,我想要插入的文本不会被插入。 我认为有什么不对的这条线在我的Python脚本...
pat = re.compile('setContentView\(R\.layout\.main\)\;')
...我已经尝试了许多不同的其他字符串进行编译。我究竟做错了什么?
感谢
'inf.close'应该是'inf.close()' –