当前位置:   article > 正文

Python常用操作_plistlib

plistlib

   在工作中偶尔会用python作为工具做进行一些文本处理或者打包脚本的工作。把用python作为工具使用的话,其逻辑也比较简单,只要找到合适的库函数就行了。这里记录的就是一些常用的操作。

   python有2.x和3.x的版本,这两个跨度较大,所以电脑上最好装两个版本,我装的是2.7和3.5。如何设置多个python版本共存呢——把某一个版本的python.exe 和 pythonw.exe 重命名,后面加个数字,并且自行修改一下系统环境变量。

   看到一般python文件,都会在开头写上下面这个,这是为了Python解释器会在解释文件的时候用,指定其编码方式

  1. #!/usr/bin/python
  2. # -*- coding: utf-8 -*-

目录

1. 对文件和文件夹的操作

2. shell命令相关

<1> execute库

3.Python的一些特性

1)入口函数

2)类中的 __getitem__ , __setitem__,__init__

4.关于编码方式

1)判断是不是带BOM的utf-8格式

2)使用不同的编码方式打开文件

5. 关于文本处理

1)去除空行和注释

6.正则匹配Re模块

1)常用的函数介绍:

2)正则字符介绍:

9.算法

1)图搜索

10. 重定向

1)输出到文件

11.读取配置

1.sys库——命令行参数

2.configparser库——配置文件

3.plistlib库——配置文件

12.一些内置函数:

1)range生成一个数值序列

13.一些常用库

0.os库

1.时间库 time 

2.压缩库 zipfile


0.import 和 from  import

1)import

import commands

引入commands模块,搜索commands.py,看看这个文件在哪

2)from  import 导入某个部分

from mod_pbxproj import XcodeProject

要导入模块 mod_pbxprojXcodeProject

搜索mod_pbxproj.py中肯定有XcodeProject。

3)模块搜索路径

当你导入一个模块,Python 解析器对模块位置的搜索顺序是:

  • 1、当前目录
  • 2、如果不在当前目录,Python 则搜索在 shell 变量 PYTHONPATH 下的每个目录。
  • 3、如果都找不到,Python会察看默认路径。UNIX下,默认路径一般为/usr/local/lib/python/。

模块搜索路径存储在 system 模块的 sys.path 变量中。变量里包含当前目录,PYTHONPATH和由安装过程决定的默认目录。

https://www.runoob.com/python/python-modules.html

ps:自己写文件名不要和已经存在的模块名字取同一个,否则当导入此模块的时候自己的写的文件会被误当作模块导入的


1. 对文件和文件夹的操作

对文件和文件夹的操作是比较多,下面记录了:

复制文件,删除文件,删除文件夹,返回文件类型(是file还是dir)以及名字,合并文件夹,移动文件夹

  1. import os
  2. #1. 复制文件
  3. def copy_file(source_file, target_file):
  4. if os.path.isfile(source_file):
  5. # open函数返回file对象
  6. # open完整参数有7个,一般都写上第一第二参数,后面需要的参数就用命名参数来指定
  7. # 第一参数 文件名,第二参数 打开模式,后面比如命名参数encoding = '' 来指定编码格式。
  8. # file对象的write写入字符串
  9. # file对象的read读出字符串
  10. open(target_file, "wb").write(open(source_file, "rb").read())
  11. #2. 删除文件
  12. def delete_file(filePath):
  13. if os.path.isfile(filePath):
  14. os.remove(filePath)
  15. #3. 删除整个文件夹
  16. def delete_dir(path):
  17. if not os.path.exists(path):
  18. return
  19. if os.path.isfile(path):
  20. return
  21. for root, dirs, files in os.walk(path, topdown=False):
  22. for f in files:
  23. os.remove(os.path.join(root, f))
  24. for folder in dirs:
  25. os.rmdir(os.path.join(root, folder))
  26. # os.rmdir() 方法用于删除指定路径的目录。仅当这文件夹是空的才可以, 否则, 抛出OSError。
  27. os.rmdir(path)
  28. #4. 合并文件夹 把source目录下的文件 合并到 target目录下。
  29. def merge_dir(source_dir, target_dir):
  30. # 列表遍历
  31. for f in os.listdir(source_dir):
  32. # f 有可能是文件也有可能是目录
  33. # target_file 有可能存在,也有可能不存在
  34. source_file = os.path.join(source_dir, f)
  35. target_file = os.path.join(target_dir, f)
  36. # 如果是文件,就拷贝
  37. if os.path.isfile(source_file):
  38. # 否定用not
  39. if not os.path.exists(target_dir):
  40. os.makedir(target_dir)
  41. open(target_file, "wb").write(open(source_file, "rb").read())
  42. # 如果是文件夹,继续递归
  43. if os.path.isdir(source_file):
  44. merge_dir(source_file, target_file)
  45. #5. 返回类型以及文件名
  46. def filetypeAndname(src):
  47. if os.path.isfile(src):
  48. index = src.rfind('\\')
  49. if index == -1:
  50. index = src.rfind('/')
  51. return 'FILE', src[index+1:]
  52. elif os.path.isdir(src):
  53. return 'DIR', ''
  54. #6. 移动文件 把source目录下以及子目录的文件 统一放到 target 根目录下。
  55. #import shutil
  56. def copy_files(source_dir, target_dir):
  57. # 列表遍历
  58. for f in os.listdir(source_dir):
  59. # f 有可能是文件也有可能是目录
  60. source_file = os.path.join(source_dir, f)
  61. # 如果是文件,就拷贝
  62. if os.path.isfile(source_file):
  63. # 否定用not
  64. if not os.path.exists(target_dir):
  65. os.makedir(target_dir)
  66. shutil.copy(source_file, target_dir)
  67. # 如果是文件夹,继续递归
  68. if os.path.isdir(source_file):
  69. copy_files(source_file, target_dir)

ps: 对目录下的每个文件进行操作的常用模式,递归操作:

  1. def dosomething_eachfile(dir):
  2. for f in os.listdir(dir):
  3. # f 有可能是文件也有可能是目录
  4. file = os.path.join(dir, f)
  5. # 如果是文件,就拷贝
  6. if os.path.isfile(file):
  7. #dosomething
  8. # 如果是文件夹,继续递归
  9. if os.path.isdir(file):
  10. dosomething_eachfile(file)

2. shell命令相关

在写工具的时候 经常用写shell命令,这里介绍的是execute库的使用,介绍了两个事例------调用unity静态函数 和 设置文件的一些权限。

<1> execute库

1)调用unity静态函数

  1. from execute import execute_command
  2. def build_unity_ios_assetBundle():
  3. cmd = unity_execute_Path + " -batchmode -quit -logfile /dev/stdout -projectPath "\
  4. + unity_project_path + " -executeMethod CommandBuild.BuildiOSAssetBundle"
  5. return execute_command(cmd, output_tag="Unity") == 0

-batchmode:命令行模式

-quit:关闭unityedtior当执行完命令

-logFile <pathname>:日志文件路径. If the path is ommitted, OSX and Linux will write output to the console. Windows uses the path %LOCALAPPDATA%\Unity\Editor\Editor.log as a default.  (/dev/stdout 标准输出。shell中执行就是输出到shell窗口)

-projectPath <pathname>:unity工程路径

-executeMethod <ClassName.MethodName>:Editor文件夹下的静态函数,一打开Unity工程就执行

 https://docs.unity3d.com/Manual/CommandLineArguments.html

2)增加文件执行权限

  1. def update_xcode_other_file(path):
  2. cmd = "chmod +x "+ path+ "/MapFileParser.sh"
  3. if not execute_cmd(cmd):
  4. print "chmod +x MapFileParser.sh fail"
  5. cmd = "chmod +x "+ path+ "/MapFileParser"
  6. if not execute_cmd(cmd):
  7. print "chmod +x MapFileParser.sh fail"

权限对象 : 档案拥有者、群组、其他。u : 表示该档案的拥有者,g 表示与该档案的拥有者属于同一个群体(group)者,o 表示其他以外的人,a 表示这三者皆是。

权限种类: r读 w写 x执行

       若要rwx属性则4+2+1=7;
  若要rw-属性则4+2=6;
  若要r-x属性则4+1=7。

权限设置符号:+ :  表示增加权限、- 表示取消权限、= 表示唯一设定权限。

chmod a=rwx file 相当于 chmod 777 file

chmod +x file 相当于 chmod a+x file

 

3.Python的一些特性

1)入口函数

  1. def main():
  2. #balabala
  3. #balabala
  4. #balabala
  5. return True
  6. if __name__ == '__main__':
  7.     main()

2)类中的 __getitem__ , __setitem__,__init__

  • __init__ 构造函数
  1. class MyTime:
  2. # 外面调用MyTime() 即调用这个函数
  3. def __init__(self):
  4. self.year = -1
  5. self.month= -1
  6. self.day = -1
  7. self.hour = -1
  8. def initWithList(self, list):
  9. if len(list) == 4:
  10. # 判断是不是int型
  11. if type(list[0]) == type(1):
  12. self.year = list[0]
  13. self.month= list[1]
  14. self.day = list[2]
  15. self.hour = list[3]
  16. def timeStamp(self):
  17. timestr = [self.year,self.month,self.day,self.hour]
  18. # 分隔符.join(列表) 把列表元素用分隔符连成字符串
  19. return '-'.join(timestr)
  • __getitem__
  • __setitem__

 

4.关于编码方式

在读取文本的时候会出现解码方式错误,下面是遇到过的一些问题

1)判断是不是带BOM的utf-8格式

  1. def IsUTF8WithBOM(file):
  2. isWithBOM = false
  3. BOM = b'\xef\xbb\xbf'
  4. existBOM = lambda s: True if s == BOM else False
  5. f = open(file, 'rb')
  6. if existBOM (f.read(3)):
  7. isWithBOM = true
  8. f.close()
  9. return isWithBOM

2)使用不同的编码方式打开文件

知道编码方式大部分都是utf16,个别文件是gbk。

如果想知道 提示的编码错误说某个位置,某个字节,用某种编码方式具体是个什么字符,可以用16进制编辑器打开文本查看。

  1. def FileLines(file):
  2. file_lines = []
  3. try:
  4. # file对象 readlines 返回列表
  5. # 同理写入 file.writelines[列表]
  6. file_lines = open(file, encoding = 'utf16').readlines()
  7. except UnicodeDecodeError:
  8. file_lines = open(file, encoding = 'gbk').readlines()
  9. except:
  10. file_lines = []
  11. return file_lines

ps:try ....except...else 语句,当没有异常发生时,else中的语句将会被执行。

 

5. 关于文本处理

1)去除空行和注释——s.strip('ab') 对s 去除a和b字符 

  1. def RemoveComment(file_lines, filename):
  2. f = open(filename, 'w')
  3. for line in file_lines
  4. # str.strip()去除前后的空格
  5. line_tmp = line.strip()
  6. # 1.len(str)字符串长度 2. str.startswith(ss)
  7. # str.find(ss) 查找ss子串在不在str中,返回索引,找不到返回-1
  8. if line_tmp.startswith('//') or not len(line_tmp)
  9. continue
  10. f.write(line)
  11. f.close()

 

6.正则匹配Re模块

正则匹配是python在处理文本的时候很重要的一个功能,用到的是Re模块,下面是一些常用函数:

1)常用的函数介绍:

1.match( rule , targetString [,flag] ) 和 search( rule , targetString [,flag] )返回一个MatchObject (如果匹配成功的话),如果匹配不成功,它们则返回一个NoneType。匹配到一个成功的,就不继续匹配了。所以在对匹配完的结果进行操作之前,你必需先判断一下是否匹配成功了。match从字符串的开头开始匹配,如果开头位置没有匹配成功,就算失败了;而search会跳过开头,继续向后寻找是否有匹配的字符串。

  1. def findFirstSubName(filename):
  2. file = open(filename).read()
  3. # 1.不能是注释的 2.可以是GotoSub("XXX") 也可以是 Sub("XXX")
  4. # 1.(?<!)前向非界定 2.*? 尽可能少的重复 3.使用括号()表示组
  5. pattern1 = '(?<!\/\/)\s*?GotoSub\("(.*?)"\)'
  6. pattern2 = '(?<!\/\/)\s*?Sub\("(.*?)"\)'
  7. hasFound = re.search(pattern1, file)
  8. # 判断是不是 NoneType 有没有找到
  9. if hasFound:
  10. # 用数字来取第一组 这里也只有一组
  11. # group(0)代表整个匹配的子串;不填写参数时,返回group(0)
  12. subname = hasFound.group(1)
  13. else:
  14. hasFound = re.search(pattern2, file)
  15. if hasFound:
  16. subname = hasFound.group(1)
  17. else:
  18. subname = None
  19. return subname

2.split( rule , target [,maxsplit] ),切片函数。使用指定的正则规则在目标字符串中查找匹配的字符串,使用匹配字符串用作为分界,把字符串切片。

  1. # 把文本内容解析成 subname 和 subcontent的字典 {subname:内容}
  2. def BuildSubDict(filename):
  3. file = open(filename).read()
  4. # 按规则先切分内容(没有注释的文件了)
  5. list_subcontent_raw = re.split('(?<!Goto)Sub\("(.*?)"\)\s*;\s*', file)
  6. if len(list_subcontent_raw) <= 1:
  7. return {}
  8. # 列表从0开始索引,[1:]排除第0个 [-1]列表的最后一个元素
  9. list_subcontent = list_subcontent_raw[1:]
  10. # 找到所有的subname
  11. pattern_subname = '(?<!Goto)Sub\("(.*?)"\)\s*;'
  12. list_subname = re.findall(pattern_subname, file)
  13. # 组成元组
  14. subpair = zip(list_subname, list_subcontent )
  15. # 组成字典
  16. subdict = {name : content for(name,content) in subpair}
  17. return subdict

findall(rule , target [,flag] ),返回一个列表,中间存放的是符合规则的字符串。如果没有符合规则的字符串被找到,就返回一个列表。

  1. # {subname:内容中的其他sub名字的列表}
  2. def BuildSubNameDict(subdict):
  3. subnamedict = {}
  4. # 遍历字典 subname是key
  5. for subname in subdict
  6. # str.split(seprate) 用seprate切分字符串
  7. list_old = subdict[subname].split('\n')
  8. list_new = []
  9. list_pattern = ['GotoSub\(\s*"(.*?)"\s*\)',\
  10. 'SetSelectDlg\(\s*&.*?&\s*,\s*(.*?)\s*\)',\
  11. 'SetSelectDlgEx\(\s*&.*?&\s*,\s*(.*?)\s*,',\
  12. 'foreach\(.*?,\s*(.*?)\s*\)',\
  13. 'foreach_new\(.*?,\s*(.*?)\s*,']
  14. # 遍历列表 line是列表元素
  15. for line in list_old:
  16. for pattern in list_pattern:
  17. matched = re.findall(pattern, line)
  18. # 空列表[] 空字典{} 都是False
  19. if matched:
  20. if matched [0] not in list_new:
  21. list_new.append(matched [0])
  22. break
  23. subnamedict[subname] = list_new

在字符串找到第一组数字

  1. def ReturnNumStr(source):
  2. found = re.search('\d+', source)
  3. if found:
  4. numstr = found.group()
  5. else:
  6. numstr = ""
  7. return numstr

2)正则字符介绍:

功能字符 ‘.’      ‘*’     ‘+’      ‘|’     ‘?’     ‘^’     ‘$’     ‘/’      等它们有特殊的功能含义。特别是’\’字符,它是转义引导符号,跟在它后面的字符一般有特殊的含义。
规则分界符

‘[‘ ‘]’     ‘(’ ‘)’       ‘{‘ ‘}’      等

‘[‘ ‘]’ 字符集合设定符号,匹配包含在其中的任意一个字符
预定义转义字符集“\d” 数字   “\w”英文字母和数字    “\s”间隔符     等等

它们是以字符’\’开头,后面接一个特定字符的形式,用来指示一个预定义好的含义。一般大写就是小写的补集。

 

ps:

\s = [ \r\n\t\v\f]   最前面有个空格。

\r : 回车CR (0D)。

\n:换行LF(0A)。

 

主流的操作系统一般使用CRLF或者LF作为其文本的换行符。其中,Windows 系统使用的是 CRLF, Unix系统(包括Linux, MacOS近些年的版本) 使用的是LF。

其它特殊功能字符’#’    ‘!’     ‘:’     ‘-‘     等它们只在特定的情况下表示特殊的含义,比如(?# …)就表示一个注释,里面的内容会被忽略。

功能字符

 |

或规则:将两个规则并列起来,它的有效范围是它两边的整条规则

如果想限定它的有效范围,必需使用一个无捕获组 ‘(?: )’包起来。比如要匹配 ‘I have a dog’或’I have a cat’,需要写成r’I have a (?:dog|cat)’ ,而不能写成 r’I have a dog|cat’

*0或多次匹配:表示匹配前面的规则0次或多次。
+1次或多次匹配:表示匹配前面的规则至少1次,可以多次匹配
?

0或1次匹配:只匹配前面的规则0次或1次。

+?  *? 尽可能少的重复匹配

>>> s= 'abbbaa'

>>> re.findall( r'a.*?a' , s) 

['abbba', 'aa']

>>> re.findall( r'a.*a' , s) 

['abbbaa']

.

匹配任意字符,除了换行符。

       >>> s=’1 \n4 \n7’

       >>> re.findall(r‘.’,s)

       ['1',' ','4',' ','7']

  
‘^’和’$’ 

匹配字符串开头和结尾,多行模式下匹配每行的开头和结尾。

>>> s= '12 34\n56 78\n90'

>>> re.findall( r'^\d+' , s , re.M )          #匹配每行位于行首的数字,re.M多行模式

['12', '56', '90']

>>> re.findall( r'\d+$' , s , re.M )          #匹配位于行尾的数字

['34', '78', '90']

 

 

规则分界符以及其它特殊功能字符

(?<!)前向非界定:希望前面的字符串不是... 的内容时候才匹配。
(?:)

无捕获组:当你要将一部分规则作为一个整体对它进行某些操作,比如指定其重复次数时,你需要将这部分规则用’(?:’ ‘)’把它包围起来。

{m,n}

匹配最少m次,最多n次。{m}  精确匹配m次 ,{m,} 大于等于m次{,n}, 小于等于n次

>>> s= ‘ 1 22 333 4444 55555 666666 ‘

>>> re.findall( r’\b\d{3}\b’ , s )            # a3位数

['333']

 

()

分组

()     无命名组,只返回了包含在’()’中的内容。

(?P<name>…)’命名组,(?P=name) 通过名字调用已匹配的命名组 。

(/number) 通过序号调用已匹配的组。

 

>>> s='aaa111aaa,bbb222,333ccc,444ddd444,555eee666,fff777ggg'

>>> re.findall( r'([a-z]+)\d+([a-z]+)' , s )             #无命名组,列表元素为元组

[('aaa', 'aaa'), ('fff', 'ggg')]

>>> re.findall( r '(?P<g1>[a-z]+)/d+(?P=g1)' , s ) #找出被中间夹有数字的前后同样的字母

['aaa']

{} 

预定义转义字符集

‘\A’和’\Z’  匹配字符串开头和结尾,在’M’模式下,它也不会匹配其它行的首尾。

\b

(\B匹配非边界)

它匹配一个单词的边界,比如空格等,不过它是一个‘0’长度字符,它匹配完的字符串不会包括那个分界的字符。

>>> s =  'abc abcde bc bcd'

>>> re.findall( r’\bbc\b’ , s )         #匹配一个单独的单词 ‘bc’ ,而当它是其它单词的一部分的时候不匹配

['bc']                                           #只找到了那个单独的’bc’

>>> re.findall( r’\sbc\s’ , s )        #匹配一个单独的单词 ‘bc’

[' bc ']                                         # 只找到那个单独的’bc’不过注意前后有两个空格,可能有点看不清楚

  

https://blog.csdn.net/smilelance/article/details/6529950

 

9.算法

1)图搜索 ps:判断是否包含某字符串 if substr in str

图用字典存,key为某个node,value为这个node可以到达的其他node。

给出一个起始点node,和指定另外一个node,判断这个指定的那个node,能不能通过起始点node达到,如果能的话,给出路径即可,不需要最短。

  1. def find_path(graphdict, extrance, target, path[]):
  2. # 1.+:两个列表相加合并 2.[]字符串变列表
  3. path = path + [extrance]
  4. if extrance == target:
  5. return path
  6. # 判断key在不在字典中 判断子串在不在字符串中也可以用in, if substr in str
  7. if target not in graphdict:
  8. return None
  9. # 遍历列表中的元素
  10. for node in graphdict[extrance]:
  11. if path and node not in path:
  12. newpath = find_path(graphdict, node, target, path)
  13. if newpath:
  14. return newpath
  15. return None

 

10. 重定向

1)输出到文件

 输出到文件中,后面使用print打印就都是输出到文件中了

  1. # a是追加
  2. f_handler = open(filename, 'w')
  3. sys.stdout = f_handler

ps: windows console把标准输出重定向到一个文件中   command > filename

 

11.读取配置

如何读取命令行参数以及如果读取配置文件

1.sys库——命令行参数

  1. import sys
  2. #命令行输入: python 文件名 argv1 argv2 argv3
  3. # 输入参数有4个,第0个参数是文件名
  4. print('参数个数为:' + len(sys.argv) + '个参数。')
  5. print('参数列表:' + str(sys.argv))

ps:读入的最后一个参数可能带有回车换行符号,所以在进行读取对比的时候进行strip()转换一下。 

2.configparser库——配置文件

test.conf文件

  1. [para1]
  2. key1 = value1
  3. key2 = value2
  4. key3 = value3
  5. [para2]
  6. key1 = value1
  7. key2 = value2
  8. key3 = value3

读取文件

  1. import configparser
  2. cf = configparser.ConfigParser()
  3. cf.read("test.conf")
  4. var1 = cf.get("para1", "key1")

3.plistlib库——配置文件

test.plist文件

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
  3. <plist version="1.0">
  4. <dict>
  5. <key>ChannelList</key>
  6. <array>
  7. <string>IOSAppstore-dev-test</string>
  8. <string>IOSAppstore-dev-official</string>
  9. </array>
  10. <key>ChannelConfig</key>
  11. <dict>
  12. <key>IOSAppstore-dev-test</key>
  13. <dict>
  14. <key>SettingFlags</key>
  15. <dict>
  16. <key>GCC_ENABLE_OBJC_EXCEPTIONS</key>
  17. <string>YES</string>
  18. </dict>
  19. <key>BuildFlags</key>
  20. <dict>
  21. <key>ENABLE_BITCODE</key>
  22. <string>NO</string>
  23. <key>ASSETCATALOG_COMPILER_LAUNCHIMAGE_NAME</key>
  24. <string>LaunchImage_dj</string>
  25. </dict>
  26. <key>OtherLDFlags</key>
  27. <array>
  28. <string>-ObjC</string>
  29. <string>-lc++.1</string>
  30. <string>-liconv</string>
  31. <string>-lz</string>
  32. </array>
  33. <key>dylibs</key>
  34. <array>
  35. <string>libz</string>
  36. <string>libstdc++.6.0.9</string>
  37. <string>libsqlite3.0</string>
  38. </array>
  39. <key>Frameworks</key>
  40. <array>
  41. <string>Security</string>
  42. <string>SystemConfiguration</string>
  43. <string>JavaScriptCore</string>
  44. <string>MobileCoreServices</string>
  45. <string>CoreTelephony</string>
  46. <string>CoreAudio</string>
  47. <string>WebKit</string>
  48. </array>
  49. </dict>
  50. <key>IOSAppstore-dev-official</key>
  51. <dict>
  52. <key>DependenceChannel</key>
  53. <string>IOSAppstore-dev-test</string>
  54. </dict>
  55. </dict>
  56. </dict>
  57. </plist>

读取文件

  1. global plistConfig
  2. global dic_channel_config
  3. global unity_build_lasttype
  4. global current_channel_name
  5. def read_plistConfig():
  6. #读取配置文件
  7. global plistConfig
  8. global dic_channel_config
  9. # 返回的是一个字典
  10. plistConfig = plistlib.readPlist('test.plist')
  11. return len(plistConfig) > 0
  12. def build_channel():
  13. # for element in list列表,plist中是array类型
  14. for current_buildchannel in plistConfig["ChannelList"]:
  15. global dic_channel_config
  16. global current_channel_name
  17. current_channel_name = current_buildchannel
  18. # 可以返回多个参数
  19. isFindChannel, dic_channel_config = getBuildingChannelConfig(current_buildchannel, {})
  20. # buildchannelDic 不一定是空
  21. # 因为有"DependenceChannel"这一项 如果找不到也算是没有找到
  22. def getBuildingChannelConfig(buildchannel, buildchannelDic):
  23. if buildchannel in plistConfig["ChannelConfig"]:
  24. dic_channel_config = plistConfig["ChannelConfig"][current_channel]
  25. if len(dic_channel_config) > 0:
  26. for currentItem in dic_channel_config:
  27. if currentItem not in buildchannelDic:
  28. buildchannelDic[currentItem] = dic_channel_config[currentItem]
  29. if "DependenceChannel" in dic_channel_config:
  30. if dic_channel_config["DependenceChannel"] == buildchannel:
  31. break;
  32. return getBuildingChannelConfig(dic_channel_config["DependenceChannel"], buildchannelDic)
  33. else:
  34. return True, buildchannelDic
  35. else:
  36. break
  37. return False, buildchannelDic

ps:

如果函数内需要修改全局变量var,需要在函数内先申明一下 global var。否则就是创建了一个 内部的局部变量var了

python如果想使用作用域之外的全局变量,可以不加global,修改一定要先声明一下是 global

 

12.一些内置函数:

1)range生成一个数值序列

 

13.一些常用库

一些比较杂比较常用的库。

0.os库

os.system(),返回值为十进制数(分别对应一个16位的二进制数)。

该函数的返回值与 linux命令返回值两者的转换关系为:

转化成16二进制数,截取其高八位,然后转乘十进制数即为 linux命令返回值。(如果低位数是0的情况下,有关操作系统的错误码共 131个,所以低位都是零)

  1. #jenkins调用脚本时需要先解锁钥匙串,此处为钥匙串密码
  2. os.system("security unlock-keychain -p cc.com")

1.时间库 time 

  1. import time
  2. def get_timestamp():
  3. # time.localtime返回struct_time对象
  4. # %Y 四位数的年份表示(000-9999)
  5. # %m 月份(01-12)
  6. # %d 月内中的一天(0-31)
  7. # %H 24小时制小时数(0-23)
  8. # %M 分钟数(00-59)
  9. # %S 秒(00-59)
  10. return time.strftime('%Y-%m-%d-%H-%M-%S', time.localtime(time.time()))

2.压缩库 zipfile——大文件 allowZip64=True

>python common_file.py zip C:\Users\ivy0709\Desktop\99999 911.zip

  1. import zipfile
  2. import sys
  3. import os
  4. def zip_dir(dirname, zipfilename):
  5. filelist = []
  6. if os.path.isfile(dirname):
  7. filelist.append(dirname)
  8. else :
  9. for root, dirs, files in os.walk(dirname):
  10. for name in files:
  11. filelist.append(os.path.join(root, name))
  12. zf = zipfile.ZipFile(zipfilename, "w", zipfile.zlib.DEFLATED, allowZip64=True)
  13. for tar in filelist:
  14. arcname = tar[len(dirname):]
  15. zf.write(tar,arcname)
  16. zf.close()
  17. if __name__ == "__main__":
  18. if sys.argv[1] == "zip":
  19. zip_dir(sys.argv[2], sys.argv[3])

3.ftp库 ftplib

  1. class Xfer(object):
  2. def __init__(self):
  3. self.ftp = None
  4. def __del__(self):
  5. pass
  6. #self.ftp.close()
  7. def setFtpParams(self, ip, uname, pwd, port, timeout):
  8. self.ip = ip
  9. self.uname = uname
  10. self.pwd = pwd
  11. self.port = port
  12. self.timeout = timeout
  13. def initEnv(self):
  14. if self.ftp is None:
  15. self.ftp = FTP()
  16. print '### connect ftp server: %s ...'%self.ip
  17. self.ftp.connect(self.ip, self.port, self.timeout)
  18. self.ftp.login(self.uname, self.pwd)
  19. print self.ftp.getwelcome()
  20. def clearEnv(self):
  21. if self.ftp:
  22. self.ftp.close()
  23. print '### disconnect ftp server: %s!'%self.ip
  24. self.ftp = None
  25. def creatdir(self,dirname,remotepath):
  26. self.initEnv()
  27. dirpath=remotepath+'/'+dirname
  28. print dirpath
  29. try:
  30. self.ftp.cwd(dirpath)
  31. except:
  32. try:
  33. self.ftp.cwd(remotepath)
  34. self.ftp.mkd(dirname)
  35. except:
  36. print "Creat directory failed!"
  37. self.clearEnv()
  38. def get_filename(self, line):
  39. pos = line.rfind(':')
  40. while(line[pos] != ' '):
  41. pos += 1
  42. while(line[pos] == ' '):
  43. pos += 1
  44. file_arr = [line[0], line[pos:]]
  45. return file_arr
  46. def get_file_list(self, line):
  47. ret_arr = []
  48. file_arr = self.get_filename(line)
  49. if file_arr[1] not in ['.', '..']:
  50. self.file_list.append(file_arr)
  51. def downloadDir(self, localdir='./', remotedir='./'):
  52. try:
  53. #print '--------%s' %(remotedir)
  54. self.ftp.cwd(remotedir)
  55. except:
  56. return
  57. if not os.path.isdir(localdir):
  58. os.makedirs(localdir)
  59. self.file_list = []
  60. self.ftp.dir(self.get_file_list)
  61. remotenames = self.file_list
  62. for item in remotenames:
  63. filetype = item[0]
  64. filename = item[1]
  65. local = os.path.join(localdir, filename)
  66. if filetype == 'd':
  67. self.download_files(local, filename)
  68. elif filetype == '-':
  69. self.download_file(local, filename)
  70. self.ftp.cwd('..')
  71. def downloadFile(self, localfile, remotefile):
  72. #return
  73. file_handler = open(localfile, 'wb')
  74. self.ftp.retrbinary('RETR %s'%(remotefile), file_handler.write)
  75. file_handler.close()
  76. def download(self,localfile, remotefile):
  77. self.initEnv()
  78. try:
  79. self.ftp.cwd(remotefile)
  80. except:
  81. #
  82. print 'It is a file:------%s' %(remotefile)
  83. self.downloadFile(localfile, remotefile)
  84. else:
  85. print "It is a dir:------"
  86. self.downloadDir(localfile, remotefile)
  87. finally:
  88. self.clearEnv()
  89. def __filetype(self, src):
  90. if os.path.isfile(src):
  91. index = src.rfind('\\')
  92. if index == -1:
  93. index = src.rfind('/')
  94. return 'FILE', src[index+1:]
  95. elif os.path.isdir(src):
  96. return 'DIR', ''
  97. def uploadDir(self, localdir='./', remotedir='./'):
  98. if not os.path.isdir(localdir):
  99. return
  100. self.ftp.cwd(remotedir)
  101. for file in os.listdir(localdir):
  102. src = os.path.join(localdir, file)
  103. if os.path.isfile(src):
  104. self.uploadFile(src, file)
  105. elif os.path.isdir(src):
  106. try:
  107. self.ftp.mkd(file)
  108. except:
  109. sys.stderr.write('the dir is exists %s'%file)
  110. self.uploadDir(src, file)
  111. self.ftp.cwd('..')
  112. def uploadFile(self, localpath, remotepath='./'):
  113. if not os.path.isfile(localpath):
  114. return
  115. print '+++ upload %s to %s:%s'%(localpath, self.ip, remotepath)
  116. self.ftp.storbinary('STOR ' + remotepath, open(localpath, 'rb'))
  117. def upload(self, src,remotepath):
  118. if (os.path.isfile(src) or os.path.isdir(src)):
  119. filetype, filename = self.__filetype(src)
  120. self.initEnv()
  121. self.ftp.cwd(remotepath)
  122. if filetype == 'DIR':
  123. self.srcDir = src
  124. self.uploadDir(self.srcDir)
  125. elif filetype == 'FILE':
  126. self.uploadFile(src, filename)
  127. self.clearEnv()
  128. else:
  129. print '+++file not find %s'%src
  130. if __name__ == "__main__":
  131. xfer = Xfer()
  132. if sys.argv[1] == "10.12.20.197":
  133. xfer.setFtpParams(ip = sys.argv[1], uname = "dddd", pwd = "dddd", port = 21, timeout = 60)
  134. elif sys.argv[1] == "10.2.4.29":
  135. xfer.setFtpParams(ip = sys.argv[1], uname = "eeeee", pwd = "eeeee", port = 888, timeout = 60)
  136. elif sys.argv[1] == "10.1.9.50":
  137. xfer.setFtpParams(ip = sys.argv[1], uname = "fffff", pwd = "fffff", port = 999, timeout = 60)
  138. if sys.argv[2] == "upload":
  139. xfer.upload(sys.argv[3],sys.argv[4])
  140. elif sys.argv[2]== "creatdir":
  141. xfer.creatdir(sys.argv[3],sys.argv[4])
  142. elif sys.argv[2]== "download":
  143. xfer.download(sys.argv[3],sys.argv[4])

 

 

 

 

 

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Monodyee/article/detail/700842
推荐阅读
相关标签
  

闽ICP备14008679号