python之模块_随手记录的模块

时间:2023-03-10 03:32:02
python之模块_随手记录的模块

目录

1、StringIO模块

2、string模块

3、pprint模块

4、struct模块

5、uuid模块

6、itertools

7、prettytable

1、StringIO

(1)使用

  from io import stringio

StringIO模块主要用于在内存缓冲区中读写数据。

1、read

用法:

s.read([n]):参数n用于限定读取的长度,类型为int,默认为从当前位置读取对象s中所有的数据。读取结束后,位置被移动。

2、readline

用法:

s.readline([length]):length用于限定读取的结束位置,类型为int,缺省为None,即从当前位置读取至下一个以'\n'为结束符的当前行。读位置被移动。

3、readlines

用法:

s.readlines():读取所有行

4、write

用法:

s.write(s):从读写位置将参数s写入到对象s。参数为str或unicode类型,读写位置被移动。

5、writeline

用法:

s.writeline(s):从读写位置将list写入给对象s。参数list为一个列表,列表的成员为str或unicode类型。读写位置被移动

6、getvalue

用法:

s.getvalue():返回对象s中的所有数据

7、truncate

用法:

s.truncate([size]):从读写位置起切断数据,参数size限定裁剪长度,默认为None

8、tell

用法:

s.tell()  #返回当前读写位置

9、seek

用法:

s.seek(pos[,mode]):移动当前读写位置至pos处,可选参数mode为0时将读写位置移动到pos处,为1时将读写位置从当前位置移动pos个长度,为2时读写位置置于末尾处再向后移动pos个长度。默认为0

10、close

用法:

s.close():释放缓冲区,执行此函数后,数据将被释放,也不可再进行操作。

11、isatty

用法:

s.isatty():此函数总是返回0。不论StringIO对象是否已被close。

12、flush

用法:

s.flush():刷新缓冲区。

StringIO模块方法

from io import StringIO  

# StringIO还有一个对应的c语言版的实现,它有更好的性能,但是稍有一点点的区别:
# cStringIO没有len和pos属性。(还有,cStringIO不支持Unicode编码)
# 如果实例化一个带有默认数据的cStringIO.StringIO类。那么该实例是read-only的;
# 无默认参数的是cStringIO.StringO,它是可读写的。cs = cStringIO.StringO() # StringIO模块主要用于在内存缓冲区中读写数据。模块是用类编写的,只有一个StringIO类,
# 所以它的可用方法都在类中。此类中的大部分函数都与对文件的操作方法类似。
s = StringIO()
s.write("www.baidu.com\n")
s.write("news.realsil.com.cn")
# getvalue() 方法用于获取写入后的str
print(s.getvalue()) # 也可以像读取文件一样读取StringIO中的数据
s.seek(0)
while True:
strBuf = s.readline()
if strBuf == "":
break print(strBuf.strip()) s.close() # 可以用一个str初始化StringIO
ss = StringIO("Hello!\nGoodBay!")
print(ss.read())
ss.close() # StringIO 模块中的函数:
# s.read([n])
# 参数n限定读取长度,int类型;缺省状态为从当前读写位置读取对象s中存储的所有数据。读取结束后,读写位置被移动。
#
# ----------------------
# s.readline([length])
# 参数length限定读取的结束位置,int类型,缺省状态为None:从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
#
# ----------------------
#
# s.readlines([sizehint])
# 参数sizehint为int类型,缺省状态为读取所有行并作为列表返回,除此之外从当前读写位置读取至下一个以“\n”为结束符的当前行。读写位置被移动。
#
# ----------------------
# s.write(s)
# 从读写位置将参数s写入给对象s。参数s为str或unicode类型。读写位置被移动。
#
# ----------------------
# s.writelines(list)
# 从读写位置将list写入给对象s。参数list为一个列表,列表的成员为str或unicode类型。读写位置被移动。
#
# ----------------------
# s.getvalue()
# 此函数没有参数,返回对象s中的所有数据。
#
# ----------------------
# s.truncate([size])
# 从读写位置起切断数据,参数size限定裁剪长度,缺省值为None。
#
# ----------------------
# s.tell()
# 返回当前读写位置。
#
# ----------------------
# s.seek(pos[,mode])
# 移动当前读写位置至pos处,可选参数mode为0时将读写位置移动至pos处,为1时将读写位置从当前位置起向后移动pos个长度,
# 为2时将读写位置置于末尾处再向后移动pos个长度;默认为0。
#
# ----------------------
# s.close()
# 释放缓冲区,执行此函数后,数据将被释放,也不可再进行操作。
#
# ----------------------
# s.isatty()
# 此函数总是返回0。不论StringIO对象是否已被close()。
#
# ----------------------
# s.flush()
# 刷新内部缓冲区。 from io import BytesIO
# StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO。
b = BytesIO()
b.write("hello".encode("utf-8"))
print(b.getvalue())
b.close()

使用

2、string

(1)使用

  import string

 """A collection of string operations (most are no longer used).

 Warning: most of the code you see here isn't normally used nowadays.
Beginning with Python 1.6, many of these functions are implemented as
methods on the standard string object. They used to be implemented by
a built-in module called strop, but strop is now obsolete itself. Public module variables: whitespace -- a string containing all characters considered whitespace
lowercase -- a string containing all characters considered lowercase letters
uppercase -- a string containing all characters considered uppercase letters
letters -- a string containing all characters considered letters
digits -- a string containing all characters considered decimal digits
hexdigits -- a string containing all characters considered hexadecimal digits
octdigits -- a string containing all characters considered octal digits
punctuation -- a string containing all characters considered punctuation
printable -- a string containing all characters considered printable """ # Some strings for ctype-style character classification
whitespace = ' \t\n\r\v\f'
lowercase = 'abcdefghijklmnopqrstuvwxyz'
uppercase = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
letters = lowercase + uppercase
ascii_lowercase = lowercase
ascii_uppercase = uppercase
ascii_letters = ascii_lowercase + ascii_uppercase
digits = ''
hexdigits = digits + 'abcdef' + 'ABCDEF'
octdigits = ''
punctuation = """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
printable = digits + letters + punctuation + whitespace # Case conversion helpers
# Use str to convert Unicode literal in case of -U
l = map(chr, xrange(256))
_idmap = str('').join(l)
del l # Functions which aren't available as string methods. # Capitalize the words in a string, e.g. " aBc dEf " -> "Abc Def".
def capwords(s, sep=None):
"""capwords(s [,sep]) -> string Split the argument into words using split, capitalize each
word using capitalize, and join the capitalized words using
join. If the optional second argument sep is absent or None,
runs of whitespace characters are replaced by a single space
and leading and trailing whitespace are removed, otherwise
sep is used to split and join the words. """
return (sep or ' ').join(x.capitalize() for x in s.split(sep)) # Construct a translation string
_idmapL = None
def maketrans(fromstr, tostr):
"""maketrans(frm, to) -> string Return a translation table (a string of 256 bytes long)
suitable for use in string.translate. The strings frm and to
must be of the same length. """
if len(fromstr) != len(tostr):
raise ValueError, "maketrans arguments must have same length"
global _idmapL
if not _idmapL:
_idmapL = list(_idmap)
L = _idmapL[:]
fromstr = map(ord, fromstr)
for i in range(len(fromstr)):
L[fromstr[i]] = tostr[i]
return ''.join(L) ####################################################################
import re as _re class _multimap:
"""Helper class for combining multiple mappings. Used by .{safe_,}substitute() to combine the mapping and keyword
arguments.
"""
def __init__(self, primary, secondary):
self._primary = primary
self._secondary = secondary def __getitem__(self, key):
try:
return self._primary[key]
except KeyError:
return self._secondary[key] class _TemplateMetaclass(type):
pattern = r"""
%(delim)s(?:
(?P<escaped>%(delim)s) | # Escape sequence of two delimiters
(?P<named>%(id)s) | # delimiter and a Python identifier
{(?P<braced>%(id)s)} | # delimiter and a braced identifier
(?P<invalid>) # Other ill-formed delimiter exprs
)
""" def __init__(cls, name, bases, dct):
super(_TemplateMetaclass, cls).__init__(name, bases, dct)
if 'pattern' in dct:
pattern = cls.pattern
else:
pattern = _TemplateMetaclass.pattern % {
'delim' : _re.escape(cls.delimiter),
'id' : cls.idpattern,
}
cls.pattern = _re.compile(pattern, _re.IGNORECASE | _re.VERBOSE) class Template:
"""A string class for supporting $-substitutions."""
__metaclass__ = _TemplateMetaclass delimiter = '$'
idpattern = r'[_a-z][_a-z0-9]*' def __init__(self, template):
self.template = template # Search for $$, $identifier, ${identifier}, and any bare $'s def _invalid(self, mo):
i = mo.start('invalid')
lines = self.template[:i].splitlines(True)
if not lines:
colno = 1
lineno = 1
else:
colno = i - len(''.join(lines[:-1]))
lineno = len(lines)
raise ValueError('Invalid placeholder in string: line %d, col %d' %
(lineno, colno)) def substitute(*args, **kws):
if not args:
raise TypeError("descriptor 'substitute' of 'Template' object "
"needs an argument")
self, args = args[0], args[1:] # allow the "self" keyword be passed
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
# Check the most common path first.
named = mo.group('named') or mo.group('braced')
if named is not None:
val = mapping[named]
# We use this idiom instead of str() because the latter will
# fail if val is a Unicode containing non-ASCII characters.
return '%s' % (val,)
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
self._invalid(mo)
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template) def safe_substitute(*args, **kws):
if not args:
raise TypeError("descriptor 'safe_substitute' of 'Template' object "
"needs an argument")
self, args = args[0], args[1:] # allow the "self" keyword be passed
if len(args) > 1:
raise TypeError('Too many positional arguments')
if not args:
mapping = kws
elif kws:
mapping = _multimap(kws, args[0])
else:
mapping = args[0]
# Helper function for .sub()
def convert(mo):
named = mo.group('named') or mo.group('braced')
if named is not None:
try:
# We use this idiom instead of str() because the latter
# will fail if val is a Unicode containing non-ASCII
return '%s' % (mapping[named],)
except KeyError:
return mo.group()
if mo.group('escaped') is not None:
return self.delimiter
if mo.group('invalid') is not None:
return mo.group()
raise ValueError('Unrecognized named group in pattern',
self.pattern)
return self.pattern.sub(convert, self.template) ####################################################################
# NOTE: Everything below here is deprecated. Use string methods instead.
# This stuff will go away in Python 3.0. # Backward compatible names for exceptions
index_error = ValueError
atoi_error = ValueError
atof_error = ValueError
atol_error = ValueError # convert UPPER CASE letters to lower case
def lower(s):
"""lower(s) -> string Return a copy of the string s converted to lowercase. """
return s.lower() # Convert lower case letters to UPPER CASE
def upper(s):
"""upper(s) -> string Return a copy of the string s converted to uppercase. """
return s.upper() # Swap lower case letters and UPPER CASE
def swapcase(s):
"""swapcase(s) -> string Return a copy of the string s with upper case characters
converted to lowercase and vice versa. """
return s.swapcase() # Strip leading and trailing tabs and spaces
def strip(s, chars=None):
"""strip(s [,chars]) -> string Return a copy of the string s with leading and trailing
whitespace removed.
If chars is given and not None, remove characters in chars instead.
If chars is unicode, S will be converted to unicode before stripping. """
return s.strip(chars) # Strip leading tabs and spaces
def lstrip(s, chars=None):
"""lstrip(s [,chars]) -> string Return a copy of the string s with leading whitespace removed.
If chars is given and not None, remove characters in chars instead. """
return s.lstrip(chars) # Strip trailing tabs and spaces
def rstrip(s, chars=None):
"""rstrip(s [,chars]) -> string Return a copy of the string s with trailing whitespace removed.
If chars is given and not None, remove characters in chars instead. """
return s.rstrip(chars) # Split a string into a list of space/tab-separated words
def split(s, sep=None, maxsplit=-1):
"""split(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the
delimiter string. If maxsplit is given, splits at no more than
maxsplit places (resulting in at most maxsplit+1 words). If sep
is not specified or is None, any whitespace string is a separator. (split and splitfields are synonymous) """
return s.split(sep, maxsplit)
splitfields = split # Split a string into a list of space/tab-separated words
def rsplit(s, sep=None, maxsplit=-1):
"""rsplit(s [,sep [,maxsplit]]) -> list of strings Return a list of the words in the string s, using sep as the
delimiter string, starting at the end of the string and working
to the front. If maxsplit is given, at most maxsplit splits are
done. If sep is not specified or is None, any whitespace string
is a separator.
"""
return s.rsplit(sep, maxsplit) # Join fields with optional separator
def join(words, sep = ' '):
"""join(list [,sep]) -> string Return a string composed of the words in list, with
intervening occurrences of sep. The default separator is a
single space. (joinfields and join are synonymous) """
return sep.join(words)
joinfields = join # Find substring, raise exception if not found
def index(s, *args):
"""index(s, sub [,start [,end]]) -> int Like find but raises ValueError when the substring is not found. """
return s.index(*args) # Find last substring, raise exception if not found
def rindex(s, *args):
"""rindex(s, sub [,start [,end]]) -> int Like rfind but raises ValueError when the substring is not found. """
return s.rindex(*args) # Count non-overlapping occurrences of substring
def count(s, *args):
"""count(s, sub[, start[,end]]) -> int Return the number of occurrences of substring sub in string
s[start:end]. Optional arguments start and end are
interpreted as in slice notation. """
return s.count(*args) # Find substring, return -1 if not found
def find(s, *args):
"""find(s, sub [,start [,end]]) -> in Return the lowest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure. """
return s.find(*args) # Find last substring, return -1 if not found
def rfind(s, *args):
"""rfind(s, sub [,start [,end]]) -> int Return the highest index in s where substring sub is found,
such that sub is contained within s[start,end]. Optional
arguments start and end are interpreted as in slice notation. Return -1 on failure. """
return s.rfind(*args) # for a bit of speed
_float = float
_int = int
_long = long # Convert string to float
def atof(s):
"""atof(s) -> float Return the floating point number represented by the string s. """
return _float(s) # Convert string to integer
def atoi(s , base=10):
"""atoi(s [,base]) -> int Return the integer represented by the string s in the given
base, which defaults to 10. The string s must consist of one
or more digits, possibly preceded by a sign. If base is 0, it
is chosen from the leading characters of s, 0 for octal, 0x or
0X for hexadecimal. If base is 16, a preceding 0x or 0X is
accepted. """
return _int(s, base) # Convert string to long integer
def atol(s, base=10):
"""atol(s [,base]) -> long Return the long integer represented by the string s in the
given base, which defaults to 10. The string s must consist
of one or more digits, possibly preceded by a sign. If base
is 0, it is chosen from the leading characters of s, 0 for
octal, 0x or 0X for hexadecimal. If base is 16, a preceding
0x or 0X is accepted. A trailing L or l is not accepted,
unless base is 0. """
return _long(s, base) # Left-justify a string
def ljust(s, width, *args):
"""ljust(s, width[, fillchar]) -> string Return a left-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces. """
return s.ljust(width, *args) # Right-justify a string
def rjust(s, width, *args):
"""rjust(s, width[, fillchar]) -> string Return a right-justified version of s, in a field of the
specified width, padded with spaces as needed. The string is
never truncated. If specified the fillchar is used instead of spaces. """
return s.rjust(width, *args) # Center a string
def center(s, width, *args):
"""center(s, width[, fillchar]) -> string Return a center version of s, in a field of the specified
width. padded with spaces as needed. The string is never
truncated. If specified the fillchar is used instead of spaces. """
return s.center(width, *args) # Zero-fill a number, e.g., (12, 3) --> '012' and (-3, 3) --> '-03'
# Decadent feature: the argument may be a string or a number
# (Use of this is deprecated; it should be a string as with ljust c.s.)
def zfill(x, width):
"""zfill(x, width) -> string Pad a numeric string x with zeros on the left, to fill a field
of the specified width. The string x is never truncated. """
if not isinstance(x, basestring):
x = repr(x)
return x.zfill(width) # Expand tabs in a string.
# Doesn't take non-printing chars into account, but does understand \n.
def expandtabs(s, tabsize=8):
"""expandtabs(s [,tabsize]) -> string Return a copy of the string s with all tab characters replaced
by the appropriate number of spaces, depending on the current
column, and the tabsize (default 8). """
return s.expandtabs(tabsize) # Character translation through look-up table.
def translate(s, table, deletions=""):
"""translate(s,table [,deletions]) -> string Return a copy of the string s, where all characters occurring
in the optional argument deletions are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256. The
deletions argument is not allowed for Unicode strings. """
if deletions or table is None:
return s.translate(table, deletions)
else:
# Add s[:0] so that if s is Unicode and table is an 8-bit string,
# table is converted to Unicode. This means that table *cannot*
# be a dictionary -- for that feature, use u.translate() directly.
return s.translate(table + s[:0]) # Capitalize a string, e.g. "aBc dEf" -> "Abc def".
def capitalize(s):
"""capitalize(s) -> string Return a copy of the string s with only its first character
capitalized. """
return s.capitalize() # Substring replacement (global)
def replace(s, old, new, maxreplace=-1):
"""replace (str, old, new[, maxreplace]) -> string Return a copy of string str with all occurrences of substring
old replaced by new. If the optional argument maxreplace is
given, only the first maxreplace occurrences are replaced. """
return s.replace(old, new, maxreplace) # Try importing optional built-in module "strop" -- if it exists,
# it redefines some string operations that are 100-1000 times faster.
# It also defines values for whitespace, lowercase and uppercase
# that match <ctype.h>'s definitions. try:
from strop import maketrans, lowercase, uppercase, whitespace
letters = lowercase + uppercase
except ImportError:
pass # Use the original versions ########################################################################
# the Formatter class
# see PEP 3101 for details and purpose of this class # The hard parts are reused from the C implementation. They're exposed as "_"
# prefixed methods of str and unicode. # The overall parser is implemented in str._formatter_parser.
# The field name parser is implemented in str._formatter_field_name_split class Formatter(object):
def format(*args, **kwargs):
if not args:
raise TypeError("descriptor 'format' of 'Formatter' object "
"needs an argument")
self, args = args[0], args[1:] # allow the "self" keyword be passed
try:
format_string, args = args[0], args[1:] # allow the "format_string" keyword be passed
except IndexError:
if 'format_string' in kwargs:
format_string = kwargs.pop('format_string')
else:
raise TypeError("format() missing 1 required positional "
"argument: 'format_string'")
return self.vformat(format_string, args, kwargs) def vformat(self, format_string, args, kwargs):
used_args = set()
result = self._vformat(format_string, args, kwargs, used_args, 2)
self.check_unused_args(used_args, args, kwargs)
return result def _vformat(self, format_string, args, kwargs, used_args, recursion_depth):
if recursion_depth < 0:
raise ValueError('Max string recursion exceeded')
result = []
for literal_text, field_name, format_spec, conversion in \
self.parse(format_string): # output the literal text
if literal_text:
result.append(literal_text) # if there's a field, output it
if field_name is not None:
# this is some markup, find the object and do
# the formatting # given the field_name, find the object it references
# and the argument it came from
obj, arg_used = self.get_field(field_name, args, kwargs)
used_args.add(arg_used) # do any conversion on the resulting object
obj = self.convert_field(obj, conversion) # expand the format spec, if needed
format_spec = self._vformat(format_spec, args, kwargs,
used_args, recursion_depth-1) # format the object and append to the result
result.append(self.format_field(obj, format_spec)) return ''.join(result) def get_value(self, key, args, kwargs):
if isinstance(key, (int, long)):
return args[key]
else:
return kwargs[key] def check_unused_args(self, used_args, args, kwargs):
pass def format_field(self, value, format_spec):
return format(value, format_spec) def convert_field(self, value, conversion):
# do any conversion on the resulting object
if conversion is None:
return value
elif conversion == 's':
return str(value)
elif conversion == 'r':
return repr(value)
raise ValueError("Unknown conversion specifier {0!s}".format(conversion)) # returns an iterable that contains tuples of the form:
# (literal_text, field_name, format_spec, conversion)
# literal_text can be zero length
# field_name can be None, in which case there's no
# object to format and output
# if field_name is not None, it is looked up, formatted
# with format_spec and conversion and then used
def parse(self, format_string):
return format_string._formatter_parser() # given a field_name, find the object it references.
# field_name: the field being looked up, e.g. "0.name"
# or "lookup[3]"
# used_args: a set of which args have been used
# args, kwargs: as passed in to vformat
def get_field(self, field_name, args, kwargs):
first, rest = field_name._formatter_field_name_split() obj = self.get_value(first, args, kwargs) # loop through the rest of the field_name, doing
# getattr or getitem as needed
for is_attr, i in rest:
if is_attr:
obj = getattr(obj, i)
else:
obj = obj[i] return obj, first

string模块源码,旧的,有些方法都找不到,估计没用了,仅做记录

string.whitespace  # ' \t\n\r\v\f'
string.ascii_lowercase # 'abcdefghijklmnopqrstuvwxyz'
string.ascii_uppercase # 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.ascii_letters # 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
string.digits # '0123456789'
string.hexdigits # '0123456789abcdefABCDEF'
string.octdigits # '01234567'
string.punctuation # """!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~"""
string.printable # '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'
# string.printable = digits + letters + punctuation + whitespace

使用

3、pprint

(1)使用( pretty printer )

  import pprint

  • pprint(object, stream=None, indent=1, width=80, depth=None, *, compact=False)
1.class pprint.PrettyPrinter(indent=1,width=80,depth=None, stream=None)
创建一个PrettyPrinter对象 indent --- 缩进,width --- 一行最大宽度, depth --- 打印的深度,这个主要是针对一些可递归的对象,如果超出指定depth,其余的用"..."代替。 eg: a=[1,2,[3,4,],5] a的深度就是2; b=[1,2,[3,4,[5,6]],7,8] b的深度就是3 stream ---指输出流对象,如果stream=None,那么输出流对象默认是sys.stdout 2.pprint.pformat(object,indent=1,width=80, depth=None) 返回格式化的对象字符串 3.pprint.pprint(object,stream=None,indent=1, width=80, depth=None) 输出格式的对象字符串到指定的stream,最后以换行符结束。 4.pprint.isreadable(object) 判断对象object的字符串对象是否可读 5.pprint.isrecursive(object) 判断对象是否需要递归的表示 eg: pprint.isrecursive(a) --->False pprint.isrecursive([1,2,3])-->True 6.pprint.saferepr(object) 返回一个对象字符串,对象中的子对象如果是可递归的,都被替换成<Recursionontypename withid=number>.这种形式。

pprint模块方法

import pprint

data = (
"this is a string", [1, 2, 3, 4], ("more tuples",
1.0, 2.3, 4.5), "this is yet another string"
) pprint.pprint(data)
'''
('this is a string',
[1, 2, 3, 4],
('more tuples', 1.0, 2.3, 4.5),
'this is yet another string')
'''
print(data)
# ('this is a string', [1, 2, 3, 4], ('more tuples', 1.0, 2.3, 4.5), 'this is yet another string')

pprint和print

(2)参考

https://blog.****.net/hxpjava1/article/details/73379642

4、struct模块

(1)使用

该模块可以把一个类型,如数字,转成固定长度的bytes

>>> struct.pack('i',1111111111111)

。。。。。。。。。

struct.error: 'i' format requires -2147483648 <= number <= 2147483647 #这个是范围

python之模块_随手记录的模块

import json,struct
#假设通过客户端上传1T:1073741824000的文件a.txt #为避免粘包,必须自定制报头
header={'file_size':1073741824000,'file_name':'/a/b/c/d/e/a.txt','md5':'8f6fbf8347faa4924a76856701edb0f3'} #1T数据,文件路径和md5值 #为了该报头能传送,需要序列化并且转为bytes
head_bytes=bytes(json.dumps(header),encoding='utf-8') #序列化并转成bytes,用于传输 #为了让客户端知道报头的长度,用struck将报头长度这个数字转成固定长度:4个字节
head_len_bytes=struct.pack('i',len(head_bytes)) #这4个字节里只包含了一个数字,该数字是报头的长度 #客户端开始发送
conn.send(head_len_bytes) #先发报头的长度,4个bytes
conn.send(head_bytes) #再发报头的字节格式
conn.sendall(文件内容) #然后发真实内容的字节格式 #服务端开始接收
head_len_bytes=s.recv(4) #先收报头4个bytes,得到报头长度的字节格式
x=struct.unpack('i',head_len_bytes)[0] #提取报头的长度 head_bytes=s.recv(x) #按照报头长度x,收取报头的bytes格式
header=json.loads(json.dumps(header)) #提取报头 #最后根据报头的内容提取真实的数据,比如
real_data_len=s.recv(header['file_size'])
s.recv(real_data_len)

用法

#_*_coding:utf-8_*_
import struct
import binascii
import ctypes values1 = (1, 'abc'.encode('utf-8'), 2.7)
values2 = ('defg'.encode('utf-8'),101)
s1 = struct.Struct('I3sf')
s2 = struct.Struct('4sI') print(s1.size,s2.size)
prebuffer=ctypes.create_string_buffer(s1.size+s2.size)
print('Before : ',binascii.hexlify(prebuffer))
# t=binascii.hexlify('asdfaf'.encode('utf-8'))
# print(t) s1.pack_into(prebuffer,0,*values1)
s2.pack_into(prebuffer,s1.size,*values2) print('After pack',binascii.hexlify(prebuffer))
print(s1.unpack_from(prebuffer,0))
print(s2.unpack_from(prebuffer,s1.size)) s3=struct.Struct('ii')
s3.pack_into(prebuffer,0,123,123)
print('After pack',binascii.hexlify(prebuffer))
print(s3.unpack_from(prebuffer,0))

简单使用

(2)参考

http://www.cnblogs.com/coser/archive/2011/12/17/2291160.html

5、uuid

(1)使用

import uuid

(2)实例

>>> import uuid

    # make a UUID based on the host ID and current time
>>> uuid.uuid1() # doctest: +SKIP
UUID('a8098c1a-f86e-11da-bd1a-00112444be1e') # make a UUID using an MD5 hash of a namespace UUID and a name
>>> uuid.uuid3(uuid.NAMESPACE_DNS, 'python.org')
UUID('6fa459ea-ee8a-3ca4-894e-db77e160355e') # make a random UUID
>>> uuid.uuid4() # doctest: +SKIP
UUID('16fd2706-8baf-433b-82eb-8c7fada847da') # make a UUID using a SHA-1 hash of a namespace UUID and a name
>>> uuid.uuid5(uuid.NAMESPACE_DNS, 'python.org')
UUID('886313e1-3b8a-5372-9b90-0c9aee199e5d') # make a UUID from a string of hex digits (braces and hyphens ignored)
>>> x = uuid.UUID('{00010203-0405-0607-0809-0a0b0c0d0e0f}') # convert a UUID to a string of hex digits in standard form
>>> str(x)
'00010203-0405-0607-0809-0a0b0c0d0e0f' # get the raw 16 bytes of the UUID
>>> x.bytes
b'\x00\x01\x02\x03\x04\x05\x06\x07\x08\t\n\x0b\x0c\r\x0e\x0f' # make a UUID from a 16-byte string
>>> uuid.UUID(bytes=x.bytes)
UUID('00010203-0405-0607-0809-0a0b0c0d0e0f')

uuid

6、itertools

(1)使用

import itertools

(2)实例

"""
itertools.product(*iterables[, repeat]) # 笛卡尔积
itertools.permutations(iterable[, r]) # 排列
itertools.combinations(iterable, r) # 组合
itertools.combinations_with_replacement(iterable, r) # 组合(包含自身重复)
""" import itertools
l = [1,2,3,4,5]
iproduct = list(itertools.product(l, repeat = 3))
ipermutations = list(itertools.permutations(l,3))
icombinations = list(itertools.combinations(l,3))
icombinations_r = list(itertools.combinations_with_replacement(l,3))
print(iproduct)
print(len(iproduct))
print(ipermutations)
print(len(ipermutations))
print(icombinations)
print(len(icombinations))
print(icombinations_r)
print(len(icombinations_r))

组合

7、prettytable

(1)使用

pip install prettytable

(2)实例

from prettytable import PrettyTable
x = PrettyTable(["name","password", "age", "gender", ])
x.align["name"] = "l" # 以name字段左对齐
x.padding_width = 1 # 填充宽度 x.add_row(["tom","",18, "M",])
x.add_row(["zhangwuji","",500, "M",])
x.add_row(["messi","",18, "M",]) print(x)
'''
+-----------+----------+-----+--------+
| name | password | age | gender |
+-----------+----------+-----+--------+
| tom | 123 | 18 | M |
| zhangwuji | 123 | 500 | M |
| messi | 123 | 18 | M |
+-----------+----------+-----+--------+
'''