python技巧分享(十三)

這是一個系列文章,主要分享python的使用建議和技巧,每次分享3點,希望你能有所收穫。

1 python2代碼轉換成python3代碼

python2代碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def greet(name):
    print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()
greet(name)

分別使用python2和python3運行python2代碼:

$ python2 2to3_demo.py
What's your name?
LEo
Hello, LEo!
$ python3 2to3_demo.py
  File "2to3_demo.py", line 6
    print "Hello, {0}!".format(name)
                      ^
SyntaxError: invalid syntax

轉換步驟如下:

$ 2to3 -w 2to3_demo.py
RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored 2to3_demo.py
--- 2to3_demo.py    (original)
+++ 2to3_demo.py    (refactored)
@@ -3,7 +3,7 @@


 def greet(name):
-    print "Hello, {0}!".format(name)
-print "What's your name?"
-name = raw_input()
+    print("Hello, {0}!".format(name))
+print("What's your name?")
+name = input()
 greet(name)
RefactoringTool: Files that were modified:
RefactoringTool: 2to3_demo.py

使用python3運行轉換後的代碼:

$ python3 2to3_demo.py
What's your name?
LEo
Hello, LEo!

轉換後的python3代碼:

#!/usr/bin/env python
# -*- coding: utf-8 -*-


def greet(name):
    print("Hello, {0}!".format(name))
print("What's your name?")
name = input()
greet(name)

python2和python3的語法有一定的區別,不能直接使用python3運行python2的代碼,官方提供了2to3工具,通過該工具(運行yum install python-tools命令安裝),可以將python2代碼自動轉換成python3代碼。由示例中可以看到,使用該工具轉換後(-w表示將轉換後的python代碼寫入文件),python2代碼就可以在python3上運行,否則會報語法錯誤。

2 python代碼反彙編

#!/usr/bin/env python
# coding=utf8

import dis


def add(a, b):
    return a + b


dis.dis(add)

運行示例如下:

$ ./dis_demo.py 
  8           0 LOAD_FAST                0 (a)
              3 LOAD_FAST                1 (b)
              6 BINARY_ADD          
              7 RETURN_VALUE        

通過標準庫dis模塊,可以反彙編python代碼,進而查看python代碼的字節碼。由示例中可以看到add函數反彙編後字節碼,通過字節碼大概能看明白該函數的具體執行過程。

3 python代碼檢測

待檢測的代碼:

 #!/usr/bin/env python

import string

shift = 3
choice = raw_input("would you like to encode or decode?")
word = (raw_input("Please enter text"))
letters = string.ascii_letters + string.punctuation + string.digits
encoded = ''
if choice == "encode":
    for letter in word:
        if letter == ' ':
            encoded = encoded + ' '
        else:
            x = letters.index(letter) + shift
            encoded=encoded + letters[x]
if choice == "decode":
    for letter in word:
        if letter == ' ':
            encoded = encoded + ' '
        else:
            x = letters.index(letter) - shift
            encoded = encoded + letters[x]

print encoded

檢測步驟如下:

$ pylint pylint_demo.py 
No config file found, using default configuration
************* Module pylint_demo
C: 16, 0: Exactly one space required around assignment
            encoded=encoded + letters[x]
                   ^ (bad-whitespace)
C:  1, 0: Missing module docstring (missing-docstring)
C:  5, 0: Constant name "shift" doesn't conform to UPPER_CASE naming style (invalid-name)
C:  6, 0: Constant name "choice" doesn't conform to UPPER_CASE naming style (invalid-name)
C:  7, 0: Constant name "word" doesn't conform to UPPER_CASE naming style (invalid-name)
C:  8, 0: Constant name "letters" doesn't conform to UPPER_CASE naming style (invalid-name)
C:  9, 0: Constant name "encoded" doesn't conform to UPPER_CASE naming style (invalid-name)

------------------------------------------------------------------
Your code has been rated at 6.32/10 (previous run: 6.32/10, +0.00)

檢測得分6.32分(滿分10分),按建議修改後的代碼如下:

# !/usr/bin/env python

'''
pylint demo code
'''

import string

SHIFT = 3
CHOICE = raw_input("would you like to encode or decode?")
WORD = (raw_input("Please enter text"))
LETTERS = string.ascii_letters + string.punctuation + string.digits
ENCODED = ''
if CHOICE == "encode":
    for LETTER in WORD:
        if LETTER == ' ':
            ENCODED = ENCODED + ' '
        else:
            x = LETTERS.index(LETTER) + SHIFT
            ENCODED = ENCODED + LETTERS[x]
if CHOICE == "decode":
    for LETTER in WORD:
        if LETTER == ' ':
            ENCODED = ENCODED + ' '
        else:
            x = LETTERS.index(LETTER) - SHIFT
            ENCODED = ENCODED + LETTERS[x]

print ENCODED

再次檢測得分10分:

$ pylint pylint_demo.py 
No config file found, using default configuration

-------------------------------------------------------------------
Your code has been rated at 10.00/10 (previous run: 6.32/10, +3.68)

由示例中可以看到,通過pylint(運行pip install pylint命令安裝)工具,在一定程度上可以檢測python代碼是否符合規範。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章