目录

一些Python小技巧

datetime.datetime.astimezone(tz=None)

返回一个使用新时区地方时的 datetime 对象。

1
2
3
4
5
6
7
8
9
from datetime import datetime, timezone, timedelta

cst_zone = timezone(timedelta(hours=8))

cst_dt = datetime(2018, 12, 20, 8, 0, 0, tzinfo=cst_zone)
utc_dt = cst_dt.astimezone(timezone.utc)

utc_dt
# datetime.datetime(2018, 12, 20, 0, 0, tzinfo=datetime.timezone.utc)

os.path.realpath

返回不含有符号链接的文件的绝对路径。

例如在当前目录中,b 软链接到 a。

1
2
3
4
5
$ touch a
$ ln -s a b
$ ls -l
-rw-r--r--  1 chi  staff     0B Dec 19 14:27 a
lrwxr-xr-x  1 chi  staff     1B Dec 19 14:27 b -> a

与 abspath 对比:

1
2
3
4
5
6
7
8
9
import os

p = './b'

r1 = os.path.realpath(p)
r2 = os.path.abspath(p)

# r1 /Users/chi/Projects/just4test/a
# r2 /Users/chi/Projects/just4test/b

raise exc from exc

一般用在 try...except... 的 except 中重新抛出错误。使用 from 会让两个错误信息中间提示不同:

不使用 from 时:

1
During handling of the above exception, another exception occurred:

使用 from 时:

1
The above exception was the direct cause of the following exception:

pytz

pytz Asia/Shanghai 时间差定义为 8 小时 6 分钟,不正确的使用会造成时间转换错误。例如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
import pytz
from datetime import datetime

utc = pytz.timezone('UTC')	# UTC
shanghai = pytz.timezone('Asia/Shanghai')	# <DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>

datetime(2019, 1, 1, 8, 0, 0, tzinfo=shanghai).astimezone(utc)
## datetime.datetime(2018, 12, 31, 23, 54, tzinfo=<UTC>)

datetime(2019, 1, 1, 0, 0, 0, tzinfo=utc).astimezone(shanghai)
# datetime.datetime(2019, 1, 1, 8, 0, tzinfo=<DstTzInfo 'Asia/Shanghai' CST+8:00:00 STD>)

os.path.expanduser(path)

在 Windows 和 Unix 系统中,将 ~ 开头的字符串路径转换为绝对路径。

1
2
3
4
import os

os.path.expanduser('~')
# '/home/invoker'

unittest 中的 setUp 和 tearDown

unitest 标准库中有三种级别的 setUp 和 tearDown:

  • setUp()tearDown() 实例方法,在每个测试方法运行前后调用;
  • setUpClass()tearDownClass() 类方法,在测试类所有方法运行前后调用一次;
  • setUpModule()tearDownModule() 函数,在模块中所有测试方法运行前后调用一次;

举个例子:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# main.py
from unittest import TestCase


def setUpModule():
    print('setUpModule')


def tearDownModule():
    print('tearDownModule')


class TestA(TestCase):
    @classmethod
    def setUpClass(cls):
        print('TestA->setUpClass')

    @classmethod
    def tearDownClass(cls):
        print('TestA->tearDownClass')

    def setUp(self):
        print('TestA->setUp')

    def tearDown(self):
        print('TestA->tearDown')

    def test_method_a(self):
        print('TestA->test_method_a')

    def test_method_b(self):
        print('TestA->test_method_b')


class TestB(TestCase):
    def test_method_c(self):
        print('TestB->test_method_c')

运行结果为:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
$ python -m unittest -q main.py
setUpModule
TestA->setUpClass
TestA->setUp
TestA->test_method_a
TestA->tearDown
TestA->setUp
TestA->test_method_b
TestA->tearDown
TestA->tearDownClass
TestB->test_method_c
tearDownModule
----------------------------------------------------------------------
Ran 3 tests in 0.000s

OK