CyanHall.com 创建于 2020-11-12, 上次更新:2021-04-30。
👉  github shields 如果有用请点赞。

1. 简单 HTTP 服务器

    python -m http.server
  

2. 创建虚拟环境

    python -m venv [venv_name]
source [venv_name]/bin/activate
deactivate

# https://mirrors.aliyun.com/pypi/simple/
# https://pypi.python.org/simple/
# --no-cache-dir
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
  

3. Hello

    # -*- coding: utf-8 -*-
# hello.py
import sys
if __name__ == '__main__':
    print("Hello ", sys.argv)
  

4. 运行 hello.py

    python hello.py world again
  

5. JSON

    import json
jsonStr1 = '{"name":"cyanhall"}'
jsonData = json.loads(jsonStr1)
jsonStr2 = json.dumps(jsonData)
jsonStr2 == jsonStr2 # True
with open('data.txt') as json_file:
    data = json.load(json_file)
with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)
  

6. XML

    # pip install xmltodict
import xmltodict

xml_dict = xmltodict.parse(xml_str)
xml_str = xmltodict.unparse(xml_dict)
  

7. Datetime

    # Convert seconds to hours, minutes and seconds
from datetime import datetime, timedelta
str(timedelta(seconds=1000))
# => '0:16:40'

datetime.fromtimestamp(1589990400)
# => datetime.datetime(2020, 5, 21, 0, 0)

now = datetime.now()
# now => datetime.datetime(2020, 5, 28, 20, 38, 16, 389862)
str(now)
# => '2020-05-28 20:38:40.493527'
now.strftime("%Y%m%d %H%M%S")
# => 20200528 203840
now.strftime("%-m/%d")
# => 5/28

# string to datetime
datetime.strptime('2020-06-03T16:17:00+0200', '%Y-%m-%dT%H:%M:%S%z')
  

8. 运行时 Debugger

    # pip install pytest
import pytest
pytest.set_trace()
  

9. 检查是否存在

    data = {'key': 'value'}
hasattr(sys, 'argv') # True
hasattr(data, 'key') # False
'key' in data # True
  

10. Delete dict key

    data = {'key': 'value'}
data.pop(key, None)
  

11. String

    name = 'Cyanhall'
name[0:4] # 'Cy'
name[-4:] # 'hall'
name.startswith('Cyan') # True
name.endswith('hall') # True
'yan' in name # True, Test string contains
  

12. Number

    n = 4
pad_n = f'{n:02}' # '04'
format(n, '.2f') # '4.00'
  

13. List

    listA = list()
listA.append('1') # ['1']
listA.pop() # return '1', listA is: []

# Sort list of dictionaries
import operator
list_of_dicts.sort(key=operator.itemgetter('name'))
  

14. 循环

    # Loop with index
for i, item in enumerate(items):
    pass
  

15. 移除文件

    import os
os.remove(path_of_file)
  

16. 重命名文件

    import os
os.rename('/path/old_filename.ext', '/path/new_filename.ext')
  

17. HTTP 请求

    import requests

# query string inlcude array
params = {'page': 1, 'include[]': ['field1', 'field2']}
requests.get(url, params)
  

18. List all decorators of class methods

    import inspect
import ast

def get_decorators(cls):
    target = cls
    decorators = {}

    def visit_FunctionDef(node):
        decorators[node.name] = []
        for n in node.decorator_list:
            name = ''
            if isinstance(n, ast.Call):
                name = n.func.attr if isinstance(n.func, ast.Attribute) else n.func.id
            else:
                name = n.attr if isinstance(n, ast.Attribute) else n.id
            decorators[node.name].append(name)

    node_iter = ast.NodeVisitor()
    node_iter.visit_FunctionDef = visit_FunctionDef
    node_iter.visit(ast.parse(inspect.getsource(target)))
    return decorators


class Foo(object):
    @baz
    @che
    def bar(self):
        pass


print(get_decorators(Foo))  # {'bar': ['baz', 'che']}
  

19. Async HTTP requests

    import asyncio
import aiohttp

# 异步下载文件
async def download_file(url, filename):
    async with aiohttp.ClientSession() as session:
        r = await session.get(url=url)
        with open(filename, "wb") as f:
            f.write(await r.read())
            f.flush()
            os.fsync(f.fileno())
    return filename

async def download_files():
    await asyncio.gather(*[asyncio.ensure_future(download_file(item)) for item in files])

loop = asyncio.new_event_loop()
loop.run_until_complete(download_files())
loop.close()
  

1. 简单 HTTP 服务器

    python -m http.server
  

3. Hello

    # -*- coding: utf-8 -*-
# hello.py
import sys
if __name__ == '__main__':
    print("Hello ", sys.argv)
  

5. JSON

    import json
jsonStr1 = '{"name":"cyanhall"}'
jsonData = json.loads(jsonStr1)
jsonStr2 = json.dumps(jsonData)
jsonStr2 == jsonStr2 # True
with open('data.txt') as json_file:
    data = json.load(json_file)
with open('data.txt', 'w') as outfile:
    json.dump(data, outfile)
  

7. Datetime

    # Convert seconds to hours, minutes and seconds
from datetime import datetime, timedelta
str(timedelta(seconds=1000))
# => '0:16:40'

datetime.fromtimestamp(1589990400)
# => datetime.datetime(2020, 5, 21, 0, 0)

now = datetime.now()
# now => datetime.datetime(2020, 5, 28, 20, 38, 16, 389862)
str(now)
# => '2020-05-28 20:38:40.493527'
now.strftime("%Y%m%d %H%M%S")
# => 20200528 203840
now.strftime("%-m/%d")
# => 5/28

# string to datetime
datetime.strptime('2020-06-03T16:17:00+0200', '%Y-%m-%dT%H:%M:%S%z')
  

9. 检查是否存在

    data = {'key': 'value'}
hasattr(sys, 'argv') # True
hasattr(data, 'key') # False
'key' in data # True
  

11. String

    name = 'Cyanhall'
name[0:4] # 'Cy'
name[-4:] # 'hall'
name.startswith('Cyan') # True
name.endswith('hall') # True
'yan' in name # True, Test string contains
  

13. List

    listA = list()
listA.append('1') # ['1']
listA.pop() # return '1', listA is: []

# Sort list of dictionaries
import operator
list_of_dicts.sort(key=operator.itemgetter('name'))
  

15. 移除文件

    import os
os.remove(path_of_file)
  

17. HTTP 请求

    import requests

# query string inlcude array
params = {'page': 1, 'include[]': ['field1', 'field2']}
requests.get(url, params)
  

19. Async HTTP requests

    import asyncio
import aiohttp

# 异步下载文件
async def download_file(url, filename):
    async with aiohttp.ClientSession() as session:
        r = await session.get(url=url)
        with open(filename, "wb") as f:
            f.write(await r.read())
            f.flush()
            os.fsync(f.fileno())
    return filename

async def download_files():
    await asyncio.gather(*[asyncio.ensure_future(download_file(item)) for item in files])

loop = asyncio.new_event_loop()
loop.run_until_complete(download_files())
loop.close()
  

2. 创建虚拟环境

    python -m venv [venv_name]
source [venv_name]/bin/activate
deactivate

# https://mirrors.aliyun.com/pypi/simple/
# https://pypi.python.org/simple/
# --no-cache-dir
pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
  

4. 运行 hello.py

    python hello.py world again
  

6. XML

    # pip install xmltodict
import xmltodict

xml_dict = xmltodict.parse(xml_str)
xml_str = xmltodict.unparse(xml_dict)
  

8. 运行时 Debugger

    # pip install pytest
import pytest
pytest.set_trace()
  

10. Delete dict key

    data = {'key': 'value'}
data.pop(key, None)
  

12. Number

    n = 4
pad_n = f'{n:02}' # '04'
format(n, '.2f') # '4.00'
  

14. 循环

    # Loop with index
for i, item in enumerate(items):
    pass
  

16. 重命名文件

    import os
os.rename('/path/old_filename.ext', '/path/new_filename.ext')
  

18. List all decorators of class methods

    import inspect
import ast

def get_decorators(cls):
    target = cls
    decorators = {}

    def visit_FunctionDef(node):
        decorators[node.name] = []
        for n in node.decorator_list:
            name = ''
            if isinstance(n, ast.Call):
                name = n.func.attr if isinstance(n.func, ast.Attribute) else n.func.id
            else:
                name = n.attr if isinstance(n, ast.Attribute) else n.id
            decorators[node.name].append(name)

    node_iter = ast.NodeVisitor()
    node_iter.visit_FunctionDef = visit_FunctionDef
    node_iter.visit(ast.parse(inspect.getsource(target)))
    return decorators


class Foo(object):
    @baz
    @che
    def bar(self):
        pass


print(get_decorators(Foo))  # {'bar': ['baz', 'che']}
  


Maitained by Cyanhall.com, Copy Rights @ CC BY-NC-SA 4.0