Cyan Hall C H
CyanHall.com 创建。上次更新:11/25/2020 👉  

1. 简单 HTTP 服务器

    python -m http.server
  

2. 创建虚拟环境

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

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

7. 运行时 Debugger

    # pip install pytest
import pytest
pytest.set_trace()
  

8. 检查是否存在

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

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

10. Number

    n = 4
pad_n = f'{n:02}' # '04'
  

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

12. 循环

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

13. 移除文件

    import os
os.remove(path_of_file)
  

14. 重命名文件

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

15. HTTP 请求

    import requests

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