环境情况如下:
python-2.5.2
python独立运行的程序中经常用到的是参数的解析,
下面使用locals()字典将输入的参数作为变量注入
paramTest.py
# coding:gbk
import os
import sys
import time
"""
python "paramTest.py" -server "127.0.0.1" -port "21" -username "corba" -password "corba" -startTime "2012-12-31 01:30:00" -endTime "2012-12-31 02:00:00" -outputDir "D:\Downloads"
"""
if __name__ == "__main__":
key = None
for i in sys.argv:
if i.startswith("-"):
key = i[1:]
elif key and not locals().has_key(key):
locals()[key] = i
print "server ", server
print "port ", port
print "username ", username
print "password ", password
print "startTime ", startTime
print "endTime ", endTime
print "outputDir ", outputDir
print
运行命令:
python "paramTest.py" -server "127.0.0.1" -port "21" -username "corba" -password "corba" -startTime "2012-12-31 01:30:00" -endTime "2012-12-31 02:00:00" -outputDir "D:\Downloads"
这一命令共注入server port username password startTime endTime outputDir
七个参数,如paramTest.py中所示,几个参数都作为变量注入到程序之中。
下面使用参数注入的技巧写一个对文本文件更改编码的程序:
fileBrowserDecodeEncode.py
# coding:gbk
import os
import sys
import time
"""
python fileBrowserDecodeEncode.py -inputDir D:\Flex\HelloFlex -outputDir D:\Flex\HelloFlex2 -fileExt .html;.xml;.mxml;.as -dec GBK -enc UTF-8
"""
def changeCode(inputDir, outputDir, fileExt=".txt;.log", dec="GBK", enc="UTF-8"):
all_exts = fileExt.split(";")
for path, dirs, files in os.walk(inputDir):
for f in files:
currname, currext = os.path.splitext(f)
if currext not in all_exts:
continue
iabsfile = path + os.sep + f
oabspath = path.replace(inputDir, outputDir)
oabsfile = oabspath + os.sep + f
print oabsfile
if not os.path.exists(oabspath):
os.makedirs(oabspath)
ifile = file(iabsfile, "r")
tdata = ifile.read()
ifile.close()
tdata = tdata.decode(dec)
tdata = tdata.encode(enc)
ofile = file(oabsfile, "w")
ofile.write(tdata)
ofile.close()
if __name__=="__main__":
key = None
for i in sys.argv:
if i.startswith("-"):
key = i[1:]
elif key and not locals().has_key(key):
locals()[key] = i
print
if not locals().has_key("fileExt"):
fileExt=".txt;.log"
if not locals().has_key("dec"):
dec="GBK"
if not locals().has_key("enc"):
enc="UTF-8"
changeCode(inputDir, outputDir, fileExt, dec, enc)
print
运行命令:
python fileBrowserDecodeEncode.py -inputDir D:\Flex\HelloFlex -outputDir D:\Flex\HelloFlex2 -fileExt .html;.xml;.mxml;.as -dec GBK -enc UTF-8
即可将 D:\Flex\HelloFlex 中的文件从 GBK 转换成 UTF-8 到 D:\Flex\HelloFlex2 目录,
只转换其中的 html、xml、mxml、as 文件,过滤了其他文件,
若不指定fileExt,默认转换txt和log文件;
若不指定dec,默认使用GBK读入;
若不指定enc,默认使用UTF-8输出。
python 参数 注入 编码 转换
比较有趣的调用:
def ppt(ip, port):
print ip, port
args1 = ("127.0.0.1", 21)
args2 = {"ip":"127.0.0.1","port":21}
ppt(*args1)
ppt(**args2)
两种方式都能自动把 ip port 参数给注入了,有意思
据说是用来替换apply的。