创建模板

来源:互联网 发布:电魂网络(603258)股吧 编辑:程序博客网 时间:2024/05/21 18:46

因为现在做的项目是lua写的,所以写了个创建lua文件的脚本。

下面贴出代码

#-*-coding:utf-8-*-#没有model、modelPanel时要自己新建模板import sysimport osmodelWord = ''modelPanelWord = ''curPath = os.getcwd()def strnset(sStr1,ch,n):sStr1 = n * ch + sStr1[n:]return sStr1def createOneLua(luaName):firstStr = luaName[0]luaName = strnset(luaName,firstStr.lower(),1)className = strnset(luaName,firstStr.upper(),1)replaceWord = ''if className.find('Panel')!=-1: replaceWord = className.replace('Panel','')content = modelPanelWordelse:replaceWord = classNamecontent = modelWordcontent = content.replace('Model',replaceWord)f=open(curPath+'\\'+luaName+'.lua','w') f.write(content)f.close()print '\n'+'create lua: '+luaName + '.lua' + '\n' +'___________________________________'def main():haveModelPanel = os.path.exists(curPath+'\\'+'modelPanel.lua') haveModel = os.path.exists(curPath+'\\'+'model.lua') if haveModelPanel==False :print '----------no modelPanel.lua--------------------'returnelif haveModel==False :print '----------no model.lua--------------------'returnmodelPanel = open(curPath+'\\'+'modelPanel.lua','r')model = open(curPath+'\\'+'model.lua','r')global modelPanelWord modelPanelWord = modelPanel.read()global modelWordmodelWord = model.read()if curPath:classNames = raw_input("Please input your classNames:\n")print '------------------------------'print 'path :'+curPathclassNames=classNames.replace(' ','')if classNames.find(',')==-1:createOneLua(classNames)else:classNameList = classNames.split(',')for className in classNameList:# 循环输出列表值createOneLua(className)else:print 'no path !!!!' modelPanel.close()model.close()os.system('pause')if __name__ == '__main__':main()

这个脚本主要到的是python自带的open()函数来对文件进行读写。

 写脚本时遇到的问题:

在对全局变量赋值时,发现在函数体内赋值后,别处调用这个全局变量的时候并不是函数体内的值。

多次试验发现,原来是要在函数体内赋值前要加个globel声明。因为不加的话会有歧义,程序会认为这个变量新定义的变量

但是要是在函数体内使用该变量并且对这个变量的元素进行赋值的话,发现是可行的。

如:在函数外定义了一个全局变量

gTemp={a=1,b=2}

在函数体内对其元素进行赋值

def  tempFunc():

gTemp.a=2

此时这个赋值是生效的

结论:不同作用域中对全局变量赋值,需要在赋值前使用global声明;通过变全局变量的引用修改元素的值不需要global声明。

原创粉丝点击