Python 經驗總結

來源:互聯網
上載者:User

標籤: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 經驗總結

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.