Created by CyanHall.com on 11/12/2020 , Last updated: 04/30/2021.
👉  github shields Star me if it’s helpful.

1. Simple HTTP Server

    python -m http.server
  

2. Create virtual environment

    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. error: invalid command 'bdist_wheel'

    pip install wheel
  

4. OSError: Could not find library geos_c or load any of its variants

    # fix: OSError: Could not find library geos_c or load any of its variants ['/Library/Frameworks/GEOS.framework/Versions/Current/GEOS', '/opt/local/lib/libgeos_c.dylib']
brew install geos
  

5. 'openssl/opensslv.h' file not found while install cryptography

    brew install openssl
env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include" pip install cryptography==3.2.1
  

6. Hello

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

7. Run hello.py

    python hello.py world again
  

8. 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)
  

9. XML

    # pip install xmltodict
import xmltodict

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

10. 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')
  

11. Runtime Debugger

    # pip install pytest
import pytest
pytest.set_trace()
  

12. Check exist

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

13. Delete dict key

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

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

15. Number

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

16. 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'))
  

17. Loop

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

18. Remove file

    import os
os.remove(path_of_file)
  

19. Rename file

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

20. HTTP requests

    import requests

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

21. 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']}
  

22. 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()
  

23. subprocess execute command

    cmd = ''
cmd_result = subprocess.run([cmd], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
if cmd_result.returncode != 0:
  err = cmd_result.stderr.decode("utf-8")
output = cmd_result.stdout.decode("utf-8")
  

1. Simple HTTP Server

    python -m http.server
  

3. error: invalid command 'bdist_wheel'

    pip install wheel
  

5. 'openssl/opensslv.h' file not found while install cryptography

    brew install openssl
env LDFLAGS="-L$(brew --prefix openssl)/lib" CFLAGS="-I$(brew --prefix openssl)/include" pip install cryptography==3.2.1
  

7. Run hello.py

    python hello.py world again
  

9. XML

    # pip install xmltodict
import xmltodict

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

11. Runtime Debugger

    # pip install pytest
import pytest
pytest.set_trace()
  

13. Delete dict key

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

15. Number

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

17. Loop

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

19. Rename file

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

21. 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']}
  

23. subprocess execute command

    cmd = ''
cmd_result = subprocess.run([cmd], stderr=subprocess.PIPE, stdout=subprocess.PIPE, shell=True)
if cmd_result.returncode != 0:
  err = cmd_result.stderr.decode("utf-8")
output = cmd_result.stdout.decode("utf-8")
  

2. Create virtual environment

    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. OSError: Could not find library geos_c or load any of its variants

    # fix: OSError: Could not find library geos_c or load any of its variants ['/Library/Frameworks/GEOS.framework/Versions/Current/GEOS', '/opt/local/lib/libgeos_c.dylib']
brew install geos
  

6. Hello

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

8. 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)
  

10. 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')
  

12. Check exist

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

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

16. 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'))
  

18. Remove file

    import os
os.remove(path_of_file)
  

20. HTTP requests

    import requests

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

22. 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()
  


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