標籤:python
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 APIbuf = StringIO(ret)line_number = 0for index, line in enumerate(buf.readlines()): if "is:" in line: line_number = index + 1 breakstatus = buf.readlines()[line_number].strip()
2、re模組,Regex模組,樣本如下:
# 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 specialfrom collections import Counterprint 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 .pyfile_list = glob.glob("%s/*/enb.py" % os.path.dirname(os.path.abspath(__file__)))
6、os.path模組
# This used for deal with file and directoryos.path.dirname(‘C:/a/b‘) --> ‘C:/a‘os.path.basename(‘C:/a/b‘) --> ‘b‘
Python 經驗總結