Python

01 - 10

01 - input与raw_input的区别

raw_input()只存在于python2.x版本中,这里也是比较python2.x版本中input与raw_input的区别。

input()  #可以直接输入数字,但输入字符的要用引号''或者双引号""
raw_input()  #将所有的输入都直接当作一串字符,可以不用加引号
  • 当输入为纯数字时:
      input返回的是数值类型,如int,float
      raw_inpout返回的是字符串类型,string类型

  • 当输入为字符串表达式时:
     input会计算在字符串中的数字表达式,而raw_input不会。
     比如:输入"57 + 3": input会得到整数60,而raw_input会得到字符串"57 + 3"

其原理如下:input的定义

def input(prompt):
    return (eval(raw_input(prompt)))

02 - 通过sys.path查看系统中的包路径

>>> import sys
>>> print sys.path

03 - Upgrade to new Python version in windows

Install the new Python version directly.
This update will replace your existing Python installation and no impact for site-packages.

04 - Upgrade python2.4 to python2.7 in CentOS-5

下载

# export http_proxy="http://10.144.1.10:8080" # 声明代理地址
# wget http://www.python.org/ftp/python/2.7.12/Python-2.7.12.tgz

处理依赖关系
RuntimeError: Compression requires the (missing) zlib module
yum install zlib
yum install zlib-devel
ImportError: cannot import name HTTPSHandler
yum install openssl openssl-devel -y

安装

# tar -xvzf Python-2.7.12.tgz
# cd Python-2.7.12
[Python-2.7.12]# ./configure
[Python-2.7.12]# make    # 根据Makefile编译源代码,连接,生成目标文件,可执行文件。
[Python-2.7.12]# make install    # 将编译成功的可执行文件安装到系统目录中,一般为/usr/local/bin目录。
[Python-2.7.12]# /usr/local/bin/python2.7 -V
[Python-2.7.12]# mv /usr/bin/python /usr/bin/python2.4.3    # 重命名原先的python
[Python-2.7.12]# ln -s /usr/local/bin/python2.7 /usr/bin/python    # 建立软连接
[Python-2.7.12]# make clean    # 仅仅是清除之前编译的可执行文件及配置文件。
[Python-2.7.12]# make distclean    # 清除所有生成的文件。

确认

# ls -l /usr/bin/python*
lrwxrwxrwx 1 root root 24 09-01 11:21 /usr/bin/python -> /usr/local/bin/python2.7
lrwxrwxrwx 1 root root 6 07-07 21:44 /usr/bin/python2 -> python
-rwxr-xr-x 2 root root 5708 2013-01-09 /usr/bin/python2.4
-rwxr-xr-x 2 root root 5708 2013-01-09 /usr/bin/python2.4.3
# python -V
Python 2.7.12

yum问题处理
解决系统python软链接指向python2.7版本后,yum不能正常工作的方法:
将/usr/bin/yum的第一行#!/usr/bin/python修改为#!/usr/bin/python2.4.3,保存修改即可

05 - Windows系统安装lxml库

lxml
http://lxml.de/

Installing lxml
http://lxml.de/installation.html

Unofficial Windows Binaries for Python Extension Packages
点击如下链接下载相应版本的安装文件,例如:lxml-3.7.2-cp27-cp27m-win_amd64.whl
http://www.lfd.uci.edu/~gohlke/pythonlibs/#lxml

D:DownLoadFilesTemp>python -m pip install lxml-3.7.2-cp27-cp27m-win_amd64.whl
Processing d:downloadfiles	emplxml-3.7.2-cp27-cp27m-win_amd64.whl
Installing collected packages: lxml
Successfully installed lxml-3.7.2

D:DownLoadFilesTemp>pip show lxml
Name: lxml
Version: 3.7.2
Summary: Powerful and Pythonic XML processing library combining libxml2/libxslt with the ElementTree API.
Home-page: http://lxml.de/
Author: lxml dev team
Author-email: lxml-dev@lxml.de
License: UNKNOWN
Location: c:python27libsite-packages
Requires:

D:DownLoadFilesTemp>

06 - 获取Python版本的新特性信息

https://docs.python.org/ » Python » Documentation » What’s New in Python

07 - Python查询whois

可以使用whois模块来进行whois查询(使用43端口,注意本地网络是否开启43端口);
例如:“print(whois.whois('http://www.csdn.net'))”

08 - Python中的赋值、浅拷贝与深拷贝

import copy

tu = (1, 2, 3)  # 不可变对象,不区分深拷贝和浅拷贝,其拷贝后的值和地址值不变
a = tu  # 值相等,地址相等
b = copy.copy(tu)  # 值相等,地址相等
c = copy.deepcopy(tu)  # 值相等,地址相等
print("### 不可变对象:", tu, id(tu))
print("浅拷贝-赋值:", a, id(a))
print("浅拷贝-copy.copy():", b, id(b))
print("深拷贝-copy.deepcopy():", c, id(c))

li = [111, 222, 333]  # 可变对象,深浅拷贝都是对源对象的复制,占用不同的内存空间
aaa = li  # 值相等,地址相等
bbb = copy.copy(li)  # 值相等,地址不相等
ccc = copy.deepcopy(li)  # 值相等,地址不相等
print("### 可变对象:", li, id(li))
print("浅拷贝-赋值:", aaa, id(aaa))
print("浅拷贝-copy.copy():", bbb, id(bbb))
print("深拷贝-copy.deepcopy():", ccc, id(ccc))

09 - 主流的Python实现方式

Python解释器
Python实际上是一门语言规范,定义应该具备哪些语言要素,应当能完成什么样的任务;
语言规范可以通过不同的方式实现,例如使用C实现,或者C++、Java、C#、JavaScript,甚至Python实现;
实现指的是符合python语言规范的解释程序以及标准库;

CPython:

  • http://cython.org/
  • http://docs.cython.org/
  • http://docs.cython.org/src/quickstart/
  • 使用C语言编写,将Python源码编译成CPython字节码,由虚拟机解释执行;
  • 是经典的标准的Python解释器,也是其他Python编译器的参考实现,通常“Python”大都是指CPython;
  • 如果需要广泛用到C编写的第三方扩展,或让Python代码能够被大多数用户直接使用,建议使用CPython;

Jython:

  • 使用Java编写在JVM上实现的Python,将Python源代码编译成Java字节码,在JVM中运行;
  • 可以在Python语言中使用JVM上其他语言编写的库和函数,反之亦然。
  • 如果在JVM上使用Python简化流程,或者在Python中使用Java代码,同时无需太多CPython扩展,推荐Jython;

IronPython:使用C#编写运行在.NET平台的Python实现,可在Python中使用.NET的库与类,反之亦然;
PyPy:研究项目,使用Python语言编写的Pyhon实现,旨在于使其能快速且方便的改进解释器;

10 - Python单语句块

如果语句块只包括单独的一句语句,那么可以在同一行指定。
单个语句是在原地立即使用的,不会被看作一个单独的块。
为了易于检查错误,尽量避免使用这种快捷方法。

>>> flag = True
>>> if flag: print('Yes')
Yes

11 - 20

11 - 通过PyMySQL连接数据库报错

错误-1:

pymysql.err.OperationalError: (2003, "Can't connect to MySQL server on '192.168.16.200' ([Errno 111] Connection refused)")

原因:MySQL服务的绑定地址并不是192.168.16.200。
处理方法:这里修改了"/etc/mysql/mysql.conf.d/mysqld.cnf"配置文件中的绑定地址为“bind-address = 192.168.16.200”。

root@Ubuntu16:~# netstat -anp |grep 3306
tcp        0      0 127.0.0.1:3306          0.0.0.0:*              LISTEN      3222/mysqld    
root@Ubuntu16:~# vim /etc/mysql/mysql.conf.d/mysqld.cnf
root@Ubuntu16:~# service mysql restart
root@Ubuntu16:~# netstat -anp |grep 3306
tcp        0      0 192.168.16.200:3306    0.0.0.0:*              LISTEN      3940/mysqld  

错误-2:

pymysql.err.OperationalError: (1045, "Access denied for user 'root'@'192.168.16.200' (using password: YES)")

原因:没有为root用户开放外部访问权限。
处理方法:允许root用户使用密码从任何主机连接到mysql服务器.

mysql> GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'anliven' WITH GRANT OPTION;
Query OK, 0 rows affected, 1 warning (0.00 sec)

12 - antigravity模块

命令行下执行“import antigravity”,可以打开漫画地址(https://xkcd.com/353/),浏览一部“关于浪漫、讽刺、数学和语言的网络漫画”(A webcomic of romance, sarcasm, math, and language.)。

13 - 不可变对象与可变对象

  • 不可变对象调用对象自身的方法,不会改变该对象自身的内容,而是创建新的对象并返回,这样就保证了不可变对象本身永远不可变;
  • 可变对象调用对象自身的方法,会改变该对象自身的内容;
  • 函数的默认参数必须指向不变对象!
st = "abc"  # string是不可变对象,变量st指向的对象内容是'abc','abc'才是字符串对象
st_new = st.replace("a", "A")  # replace方法创建一个新字符串并返回,并没有改变对象内容
print("after: ", st, st_new)

li = ['333', '222', '111']  # list是可变对象
li_new = li.sort()  # sort方法改变对象自身内容,没有返回值
print("after: ", li, li_new)

结果

after:  abc Abc
after:  ['111', '222', '333'] None

14 - “future”模块

Python的新版本中会引入新的功能特性,或者对原来的功能特性作一些改动。
而有些改动是不兼容旧版本的,也就是说,在当前版本运行正常的代码,在新版本中就无法正常运行。
Python的__future__模块,可以把下一个新版本的特性导入到当前版本,这样就可以在当前版本中测试一些新版本的特性。

一般情况下,都是利用__future__模块在Python 2.x环境中对Python 3.x的特性做试用和验证。

$ py -2
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> 2 / 3
0
>>> 2.0 / 3
0.6666666666666666
>>>
>>> from __future__ import division
>>> 2 / 3
0.6666666666666666
>>> 2.0 / 3
0.6666666666666666
>>> 2 // 3
0
>>>
>>> import __future__
>>> dir(__future__)
['CO_FUTURE_ABSOLUTE_IMPORT', 'CO_FUTURE_DIVISION', 'CO_FUTURE_PRINT_FUNCTION', 'CO_FUTURE_UNICODE_LITERALS', 'CO_FUTURE_WITH_STATEMENT', 'CO_GENERATOR_ALLOWED', 'CO_NESTED', '_Feature', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '__package__', 'absolute_import', 'all_feature_names', 'division', 'generators', 'nested_scopes', 'print_function', 'unicode_literals', 'with_statement']
>>> help(__future__)
Help on module __future__:

NAME
    __future__ - Record of phased-in incompatible language changes.
......

15 - Python实现斐波那契数列

def fab(x):
    s = [1, 2]
    for i in range(x - 2):
        s.append(s[-1] + s[-2])
    return (s)


print(fab(5))


def fab2(max):
    n, a, b = 0, 0, 1
    while n < max:
        a, b = b, a + b
        print(b)
        n += 1

fab2(5)

16 - 标准库os模块的常用方法

os.remove()                     删除文件
os.rename()                     重命名文件
os.walk()                       生成目录树下的所有文件名
os.chdir()                      改变目录
os.mkdir/makedirs               创建目录/多层目录
os.rmdir/removedirs             删除目录/多层目录
os.listdir()                    列出指定目录的文件
os.getcwd()                     取得当前工作目录
os.chmod()                      改变目录权限
os.path.basename()              去掉目录路径,返回文件名
os.path.dirname()               去掉文件名,返回目录路径
os.path.join()                  将分离的各部分组合成一个路径名
os.path.split()                 返回(dirname(),basename())元组
os.path.splitext()              (返回filename,extension)元组
os.path.getatimectimemtime    分别返回最近访问、创建、修改时间
os.path.getsize()               返回文件大小
os.path.exists()                是否存在
os.path.isabs()                 是否为绝对路径
os.path.isdir()                 是否为目录
os.path.isfile()                是否为文件

17 - 标准库sys模块的常用方法

sys.argv                   命令行参数List,第一个元素是程序本身路径 
sys.modules.keys()         返回所有已经导入的模块列表 
sys.exc_info()             获取当前正在处理的异常类,exc_type、exc_value、exc_traceback当前处理的异常详细信息 
sys.exit(n)                退出程序,正常退出时exit(0) 
sys.hexversion             获取Python解释程序的版本值,16进制格式如:0x020403F0 
sys.version                获取Python解释程序的版本信息 
sys.maxint                 最大的Int值 
sys.maxunicode             最大的Unicode值 
sys.modules                返回系统导入的模块字段,key是模块名,value是模块 
sys.path                   返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值 
sys.platform               返回操作系统平台名称 
sys.stdout                 标准输出
sys.stdin                  标准输入
sys.stderr                 错误输出
sys.exc_clear()            用来清除当前线程所出现的当前的或最近的错误信息
sys.exec_prefix            返回平台独立的python文件安装的位置
sys.byteorder              本地字节规则的指示器,big-endian平台的值是'big',little-endian平台的值是'little'
sys.copyright              记录python版权相关的东西
sys.api_version            解释器的C的API版本
sys.version_info           python版本信息

18 - 报错“Microsoft Visual C++ 14.0 is required”

问题现象:
使用pip安装line_profiler时,报错“error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools”。

guowli@5CG450158J MINGW64 /d/CI-Git-Files
$ pip3 install line_profiler --proxy="10.144.1.10:8080"
......
......
......
Requirement already satisfied: ipython-genutils in c:python36libsite-packages (from traitlets>=4.2->IPython>=0.13->line_profiler) (0.2.0)
Installing collected packages: line-profiler
  Running setup.py install for line-profiler ... error
......
......
......
    error: Microsoft Visual C++ 14.0 is required. Get it with "Microsoft Visual C++ Build Tools": http://landinghub.visualstudio.com/visual-cpp-build-tools
......
......
......

处理方法:
改用离线安装方式。在(http://www.lfd.uci.edu/~gohlke/pythonlibs/)下载对应Python模块的运行环境,并在命令行下安装。
示例:
找到第三方库line_profiler的对应版本的离线安装包(https://www.lfd.uci.edu/~gohlke/pythonlibs/#line_profiler)
在命令行下,安装此运行环境:pip3 install line_profiler-2.1.2-cp36-cp36m-win_amd64.whl

19 - 常用于数据类型转换的内置函数(Python3)

Binary Sequence Types

  • bytes():Return a new “bytes” object.
  • bytearray():Return a new array of bytes.
  • memoryview(obj):Return a “memory view” object created from the given argument.

Numeric Types

  • int(): Return an integer object constructed from a number or string.
  • float(): Return a floating point number constructed from a number or string
  • complex(): Return a complex number.

Iterator Types

  • iter(): Return an iterator object.

Text Sequence Type

  • str(): Return a str version of object.
  • repr(): Return a string containing a printable representation of an object.

Sequence Types

  • list()
  • tuple()
  • range()

Mapping Types

  • dict()

Set Types

  • set(): Return a new set object, optionally with elements taken from iterable.
  • frozenset(): Return a new frozenset object, optionally with elements taken from iterable.

Others

  • bin(x): Convert an integer number to a binary string prefixed with “0b”.
  • bool([x]): Return a Boolean value, i.e. one of True or False.
  • ord(c): Given a string representing one Unicode character, return an integer.
  • chr(i): Return the string representing a character whose Unicode code point is the integer i.
  • oct(x): Convert an integer number to an octal string prefixed with “0o”.
  • hex(x): Convert an integer number to a lowercase hexadecimal string prefixed with “0x”.

20 - pipenv

尽管 pip 可以安装 Python 包, 但仍推荐使用 Pipenv,因为它是一种更高级的工具,可简化依赖关系管理的常见使用情况;

Pipenv:Python Dev Workflow for Humans
- HomePage:https://github.com/pypa/pipenv
- Docs:https://docs.pipenv.org/
- Basics:https://docs.pipenv.org/basics/

参考信息
- Pipenv & 虚拟环境:https://pythonguidecn.readthedocs.io/zh/latest/dev/virtualenvs.html

21 - 30

21 - 查看Python环境是否是64位

方法:1:查看提示信息

$ python
Python 2.7.12 (v2.7.12:d33e0cf91556, Jun 27 2016, 15:24:40) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

$ py -3
Python 3.7.1 (default, Dec 10 2018, 22:54:23) [MSC v.1915 64 bit (AMD64)] :: Anaconda, Inc. on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> exit()

方法2:查看platform信息

>>> import platform
>>> platform.architecture()
('64bit', 'WindowsPE')

22 - 查看对象的内存占用

import sys
x = 1  # 一个32比特的整数在 Python3中占用28字节
print(sys.getsizeof(x))
原文地址:https://www.cnblogs.com/anliven/p/6085547.html