Python小技巧

1:

    urlps = urlparse.urlparse(RtmpServer)
    HOST = urlps.hostname
    if urlps.port:
        PORT = urlps.port
    else:
        PORT = 1935

urlps.port要么为None,要么为一个非0的整数,所以最后的if else可以这样写:

PORT = urlps.port or 1935

2: 使用带步进反向切片翻转字符串

>>> astr = "hello,world"
>>> astr[::-1]
'dlrow,olleh'

3:使用subprocess启动子进程,在父进程(正常或非正常)终止时,保证子进程也退出的方法:

import signal
import ctypes
libc = ctypes.CDLL("libc.so.6")
def set_pdeathsig(sig = signal.SIGTERM):
    PR_SET_PDEATHSIG = 1
    def callable():
        return libc.prctl(PR_SET_PDEATHSIG, sig)
    return callable
p = subprocess.Popen(args, preexec_fn = set_pdeathsig(signal.SIGTERM))

 这里其实主要是调用Linux下的系统调用prctl实现的。因此这种方法只适合于linux系统。

4:查看python标准库源码:

https://github.com/python/cpython

5:

原文地址:https://www.cnblogs.com/gqtcgq/p/8006125.html