This is all the knowledge learned from others’ code. We can learn it together.
1、StringIO模块,将输入测字符串作为流返回,可以进行迭代,示例如下:
# change the string to in memory stream, the detailed info can find in Python API
buf = StringIO(ret)
line_number = 0
for index, line in enumerate(buf.readlines()):
if "is:" in line:
line_number = index + 1
break
status = buf.readlines()[line_number].strip()
2、re模块,正则表达式模块,示例如下:
# the regular expression below used for split string to a list by one or more whitespace.
for line in ret.split("\n"):
if ‘rrc‘ in line and flag:
flag = False
column_of_rrc = re.split(r‘\s+‘, line.strip()).index(‘rrc‘)
continue
if "UEC-1 |" in line:
stats = re.split(r‘\s+‘, line.strip())[column_of_rrc + 1]
break
3、subprocess模块,用于启动操作系统上的shell命令行,并可以返回执行的结果
# with the subprocess to execute the command.
# Popen.returncode
# The child return code, set by poll() and wait() (and indirectly by communicate()). A None
# value indicates that the process hasn’t terminated yet.
decode_result = subprocess.Popen(decode_cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
start = datetime.datetime.now()
decode_log = "start to decode log.\n\r"
while decode_result.poll() is None:
for line in decode_result.stdout.readlines():
decode_log += line
time.sleep(1)
if (datetime.datetime.now() - start).seconds > timeout:
failed_reason = "decode run timeout"
self._log.error(failed_reason)
rc = decode_result.returncode
self._log.info("timeout,return code is %s" % rc)
istimeout = True
ctypes.windll.kernel32.TerminateProcess(int(decode_result._handle), -1)
break
4、collections集合相关
# the use is special
from collections import Counter
print Counter("hello")
>>> Counter({‘l‘: 2, ‘h‘: 1, ‘e‘: 1, ‘o‘: 1})
5、 glob模块
# list all the file enb.py, can with wildchar, like * etc.
# glob.glob(‘*.py‘) can list all file under current path endwiths .py
file_list = glob.glob("%s/*/enb.py" % os.path.dirname(os.path.abspath(__file__)))
6、os.path模块
# This used for deal with file and directory
os.path.dirname(‘C:/a/b‘) --> ‘C:/a‘
os.path.basename(‘C:/a/b‘) --> ‘b‘
原文:http://blog.csdn.net/u011233383/article/details/45244231