分类 python 下的文章


语法:

subprocess.check_output(args, *, stdin=None, stderr=None, shell=False, universal_newlines=False)

执行cmd命令并返回结果到字符串。

用法:

import subprocess

output = check_output(["cat", "/etc/hostname"]).strip()
print(output)

以上脚本会执行 cat /etc/hostname 命令然后将结果赋值给 output 变量。
strip() 可以将 string 的前后空格去掉。



To transform a unicode string to a byte string in Python do this:

>>> 'foo'.encode('utf_8')
b'foo'

To transform a byte string to a unicode string:

>>> b'foo'.decode('utf_8')
'foo'

  1. To convert a string to bytes.

    data = ""               #string
    data = "".encode()      #bytes
    data = b""              #bytes
  2. To convert bytes to a String.

    data = b""              #bytes
    data = b"".decode()     #string
    data = str(b"")         #string

str to hex:

import codecs
hexlify = codecs.getencoder('hex')
hexlify(b'Blaah')[0]

out:

b'426c616168'

hex to str:

import codecs
decode_hex = codecs.getdecoder("hex_codec")
s = decode_hex(b'426c616168')[0]

out:

b'Blaah'