Python必知必会的常用代码

设定退出函数

atexit.register(lamda x:None)

删除目录

import shutil,os
shutil.rmtree("path2dir")
try:
    os.remove("path2file")
    os.rmdir("path2dir")
except os.error:
    pass

获取临时目录

import tempfile
temp_dir=tempfile.mkdtemp()

检测操作系统信息

IS_WINDOWS = os.name == 'nt'
IS_CYGWIN = os.name == 'posix' and 'CYGWIN' in os.uname()[0]

标准输入输出

message = (
        'test1\n'
        'test2\n'
        'test3\n')
sys.stdout.write(message)
sys.exit(1)

执行shell命令

import subprocess
p = subprocess.Popen(command,
                     stdout=subprocess.PIPE, stderr=stderr,
                     cwd=working_dir, universal_newlines=True, env=env)
# communicate returns a tuple with the file obect for the child's
# output.
self.output = p.communicate()[0]
self._return_code = p.returncode

Exception

try:
    pass
except Exception as e:
    pass
finally:
    pass

MD5 计算

file = open('path2file', 'rb')
bytes = file.read()
file.close()
hash = hashlib.md5()
hash.update( bytes)
md5 = hash.hexdigest()

XML 操作

from xml.dom import minidom, Node

element=parse("foo.xml")
element=parseString("<foo><bar/></foo>")
if element.tagName == 'testsuites':
    timestamp = element.getAttributeNode('timestamp')
    timestamp.value = re.sub(r'^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d$',
                             '*', timestamp.value)
    if element.tagName in ('testsuites', 'testsuite', 'testcase'):
        time = element.getAttributeNode('time')
        time.value = re.sub(r'^\d+(\.\d+)?$', '*', time.value)
        type_param = element.getAttributeNode('type_param')
        if type_param and type_param.value:
            type_param.value = '*'
        elif element.tagName == 'failure':
            source_line_pat = r'^.*[/\\](.*:)\d+\n'
            # Replaces the source line information with a normalized form.
            message = element.getAttributeNode('message')
            message.value = re.sub(source_line_pat, '\\1*\n', message.value)
            for child in element.childNodes:
                if child.nodeType == Node.CDATA_SECTION_NODE:
                    # Replaces the source line information with a normalized form.
                    cdata = re.sub(source_line_pat, '\\1*\n', child.nodeValue)
                    # Removes the actual stack trace.
                    child.nodeValue = re.sub(r'\nStack trace:\n(.|\n)*',
                                             '', cdata)
     for child in element.childNodes:
        if child.nodeType == Node.ELEMENT_NODE:
            self.NormalizeXml(child)

json 数据处理

import json
json.dumps(dict(a=5))

tar 文件处理

import tarfile
import tarfile.TarFile

target = os.path.join(moduledir, ZONEFILENAME)
with TarFile.open(target, "w:%s" % format) as tf:
    for entry in os.listdir(zonedir):
        entrypath = os.path.join(zonedir, entry)
        tf.add(entrypath, entry)
with TarFile.open(filename) as tf:
    for name in zonegroups:
        tf.extract(name, tmpdir)

tar_file = tarfile.open(file_name, "r")
tar_file_list = tar_file.getnames()
emod_list = list(filter(lambda x: x.endswith('emod'), tar_file_list))
conf_list = list(filter(lambda x: x.endswith('conf'), tar_file_list))
if len(emod_list) == 0 or len(conf_list) == 0:
    raise Exception('not find emod file or conf file')

    if len(conf_list) > 1:
        raise Exception('conf file too much')
    extract_dir = os.path.join(self.path, os.path.basename(conf_list[0].rsplit(".", 1)[0]))

Zip文件处理

import zipfile

with zipfile.ZipFile(filename, 'r') as zipObj:
    listOfFileNames = zipObj.namelist()
    for fileName in listOfFileNames:
        zipObj.extract(fileName, output_dir)

 with zipfile.ZipFile(out, 'w', zipfile.ZIP_DEFLATED) as f:
        for input_it in zip_inputs:
            if os.path.isdir(input_it):
                for dirpath, dirnames, filenames in os.walk(input_it):
                    for filename in filenames:
                        to_zip = os.path.join(dirpath, filename)
                        if os.path.exists(to_zip):
                            f.write(to_zip)
            else:
                if os.path.exists(input_it):
                    f.write(input_it)

Logging

import logging
logger = logging.getLogger()
logger.setLevel(log_level)
formatter = logging.Formatter("%(asctime)s   %(levelname)s: %(message)s")

if log_path and len(log_path):
    fh = logging.FileHandler(log_path, mode='a', encoding="utf8")
    fh.setLevel(log_level)
    fh.setFormatter(formatter)
    logger.addHandler(fh)

ch = logging.StreamHandler()
ch.setLevel(log_level)
ch.setFormatter(formatter)
logger.addHandler(ch)

查看python 版本信息

if sys.version_info >= (3, 0):
    pass

查看文件信息

file_stats = os.stat(file_name)
# create a dictionary to hold file info
file_info = {
    'fname': file_name,
    'fsize': file_stats[stat.ST_SIZE],
    'f_lm': time.strftime("%d/%m/%Y %I:%M:%S %p",
                          time.localtime(file_stats[stat.ST_MTIME])),
    'f_la': time.strftime("%d/%m/%Y %I:%M:%S %p",
                          time.localtime(file_stats[stat.ST_ATIME])),
    'f_ct': time.strftime("%d/%m/%Y %I:%M:%S %p",
                          time.localtime(file_stats[stat.ST_CTIME])),
    'no_of_lines': count,
    't_char': t_char
}

查看系统信息

import platform as pl

profile = [
    'architecture',
    'linux_distribution',
    'mac_ver',
    'machine',
    'node',
    'platform',
    'processor',
    'python_build',
    'python_compiler',
    'python_version',
    'release',
    'system',
    'uname',
    'version',
]

class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'

for key in profile:
    if hasattr(pl, key):
        print(key + bcolors.BOLD + ": " + str(getattr(pl, key)()) + bcolors.ENDC)
标签:

About: kiah


7 thoughts on “Python必知必会的常用代码”

  1. I am glad for writing to make you know what a incredible encounter my friend’s girl gained studying your web page. She learned plenty of pieces, which include what it’s like to possess an awesome helping mood to let other folks smoothly know just exactly several multifaceted subject matter. You truly exceeded our own expectations. Thank you for offering these necessary, safe, explanatory and even fun tips about this topic to Julie.

  2. I precisely needed to appreciate you once again. I am not sure the things that I might have gone through in the absence of the entire opinions documented by you directly on such a problem. It had been a very frightening difficulty in my circumstances, however , looking at the skilled manner you managed that made me to jump over fulfillment. I am happier for this help and even hope you find out what an amazing job you have been putting in training the mediocre ones via your webpage. Most probably you haven’t met any of us.

  3. I am glad for writing to make you know what a incredible encounter my friend’s girl gained studying your web page. She learned plenty of pieces, which include what it’s like to possess an awesome helping mood to let other folks smoothly know just exactly several multifaceted subject matter. You truly exceeded our own expectations. Thank you for offering these necessary, safe, explanatory and even fun tips about this topic to Julie.

  4. Thanks for the recommendations on credit repair on this amazing site. A few things i would tell people is always to give up the particular mentality they can buy today and shell out later. Like a society we all tend to try this for many issues. This includes getaways, furniture, and also items we wish. However, you should separate the wants out of the needs. While you’re working to raise your credit score make some sacrifices. For example it is possible to shop online to save cash or you can visit second hand retailers instead of pricey department stores regarding clothing.

  5. I’m just commenting to let you be aware of of the fabulous discovery my cousin’s daughter experienced going through your site. She even learned lots of issues, most notably how it is like to have a very effective giving mindset to have many others just gain knowledge of chosen grueling matters. You really did more than our desires. Many thanks for distributing the important, healthy, educational and as well as easy thoughts on the topic to Gloria.

发表评论

电子邮件地址不会被公开。