Python - Tips

01 - 10

01 - input與raw_input的區別

raw_input()只存在於python2.x版本中,這裏也是比較python2.x版本中input與raw_input的區別。html

input()  #能夠直接輸入數字,但輸入字符的要用引號''或者雙引號""
raw_input()  #將全部的輸入都直接看成一串字符,能夠不用加引號
  • 當輸入爲純數字時:
      input返回的是數值類型,如int,float
      raw_inpout返回的是字符串類型,string類型python

  • 當輸入爲字符串表達式時:
     input會計算在字符串中的數字表達式,而raw_input不會。
     好比:輸入"57 + 3": input會獲得整數60,而raw_input會獲得字符串"57 + 3"mysql

其原理以下:input的定義git

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.github

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

下載web

# 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 -ysql

安裝數據庫

# 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    # 清除全部生成的文件。

確認vim

# 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,保存修改便可windows

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:\DownLoadFiles\Temp>python -m pip install lxml-3.7.2-cp27-cp27m-win_amd64.whl
Processing d:\downloadfiles\temp\lxml-3.7.2-cp27-cp27m-win_amd64.whl
Installing collected packages: lxml
Successfully installed lxml-3.7.2

D:\DownLoadFiles\Temp>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:\python27\lib\site-packages
Requires:

D:\DownLoadFiles\Temp>

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.getatime\ctime\mtime    分別返回最近訪問、建立、修改時間
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:\python36\lib\site-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))
相關文章
相關標籤/搜索