我想寫一個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()' –