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


136 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.

  6. Thanks for your ideas. One thing I have noticed is that banks and financial institutions know the spending habits of consumers and understand that most people max out their credit cards around the holidays. They wisely take advantage of this fact and start flooding your inbox and snail-mail box with hundreds of 0 APR credit card offers soon after the holiday season ends. Knowing that if you are like 98% of the American public, you’ll jump at the chance to consolidate credit card debt and transfer balances to 0 APR credit cards. aaaaaaa https://headachemedi.com – buy Headache pain drugs

  7. Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.

  8. I figured out more interesting things on this weight-loss issue. One particular issue is a good nutrition is especially vital while dieting. A tremendous reduction in junk food, sugary food, fried foods, sweet foods, beef, and bright flour products could possibly be necessary. Possessing wastes organisms, and harmful toxins may prevent ambitions for fat-loss. While selected drugs for the short term solve the challenge, the horrible side effects are certainly not worth it, and they also never present more than a non permanent solution. It is just a known idea that 95% of diet plans fail. Many thanks for sharing your thinking on this blog site. https://osteoporosismedi.com buy osteoporosis medication

  9. Dzięki za sugestii dotyczących naprawy kredytu na temat tego konkretnego sieci -teren. Rzeczy i chciałbym zaoferować jako rada ludziom oznacza zwykle zrezygnować z tej mentalności że w tym momencie i rozwidź później. Being a as be a} społeczeństwo {my|my wszyscy|my wszyscy|wielu z nas|większość z nas|większość ludzi} ma tendencję do {robienia tego|robienia tamtego|próbowania tego|zdarzyć się|powtórz to} dla wielu {rzeczy|problemów|czynników}. Obejmuje to {wakacje|wakacje|wypady|wyjazdy wakacyjne|wycieczki|rodzinne wakacje}, meble, {i|jak również|a także|wraz z|oprócz|plus} przedmiotów {chcemy|chcielibyśmy|życzymy|chcielibyśmy|naprawdę chcielibyśmy to mieć}. Jednak {musisz|musisz|powinieneś|powinieneś chcieć|wskazane jest, aby|musisz} oddzielić {swoje|swoje|to|twoje obecne|swoje|osoby} chcą {od wszystkich|z potrzeb|z}. {Kiedy jesteś|Kiedy jesteś|Kiedy jesteś|Jeśli jesteś|Tak długo, jak jesteś|Kiedy} pracujesz, aby {poprawić swój kredyt|poprawić swoją zdolność kredytową|zwiększyć swój kredyt|zwiększyć swój kredyt|podnieś swój ranking kredytowy|popraw swój kredyt} wynik {musisz zrobić|zrobić|faktycznie potrzebujesz|naprawdę musisz} dokonać kilku {poświęceń|kompromisów}. Na przykład {możesz|możesz|możesz|możesz|będziesz mógł|| możesz|prawdopodobnie możesz} robić zakupy online {aby zaoszczędzić pieniądze|aby zaoszczędzić pieniądze|aby zaoszczędzić} lub {możesz przejść do|może się zwrócić|może odwiedzić|może obejrzeć|może sprawdzić|może kliknąć} używane {sklepy|sklepy|detaliści|sprzedawcy|punkty sprzedaży|dostawcy} zamiast {drogie|drogie|drogie|drogie|drogie|drogich} domów towarowych {dla|w odniesieniu do|dotyczących|odnoszących się do|przeznaczonych dla|do zdobycia} odzieży {strzykawki insulinowe 1ml|strzykawki tuberkulinowe|strzykawki|strzykawka|strzykawki insulinowe|strzykawki do insuliny|strzykawki trzyczęściowe tuberkulinowe|strzykawka tuberkulinowa|strzykawka insulinowa|strzykawka do insuliny|strzykawka trzyczęściowe tuberkulinowa} {strzykawki insulinowe 1ml|strzykawki tuberkulinowe|strzykawki|strzykawka|strzykawki insulinowe|strzykawki do insuliny|strzykawki trzyczęściowe tuberkulinowe|strzykawka tuberkulinowa|strzykawka insulinowa|strzykawka do insuliny|strzykawka trzyczęściowe tuberkulinowa}.

  10. Холостячка 2 сезон https://bit.ly/39ioLkW Смотреть онлайн шоу Холостячка 2 сезон на СТБ.
    Пост шоу можно смотреть тут. Холостячка стб 2 сезон 1-2 серия

  11. Холостячка 2 сезон https://bit.ly/39ioLkW Смотреть онлайн шоу Холостячка 2 сезон на СТБ.
    Пост шоу можно смотреть тут. Холостячка стб 2 сезон 1-2 серия

  12. Холостячка 2 сезон https://bit.ly/39ioLkW Смотреть онлайн шоу Холостячка 2 сезон на СТБ.
    Пост шоу можно смотреть тут. Холостячка стб 2 сезон 1-2 серия

发表评论

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