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 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 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代码是否符合规范。

LEo at 00:05

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏潇涧技术专栏

Lint Tool Analysis (1)

本系列的几篇源码分析文档意义不大,如果你正好也在研究lint源码,或者你想知道前面自定义lint规则中提出的那几个问题,抑或你只是想大致了解下lint的源码都有...

701
来自专栏逆向技术

64位内核第二讲,进程保护之对象钩子

         64位内核第二讲,进程保护. 一丶什么是保护. 什么是保护. 比如我们安装了xxx杀毒软件.那么此时你用任务管理器关闭.是关闭不了的.原因是内...

3126
来自专栏dotnet core & Spring boot

讲一下Asp.net core MVC2.1 里面的 ApiControllerAttribute

ASP.NET Core MVC 2.1 特意为构建 HTTP API 提供了一些小特性,今天主角就是 ApiControllerAttribute. (注:文...

1202
来自专栏Golang语言社区

用Go实现一门解释型语言

A interpreter language implementation in Go

832
来自专栏技术记录

前端插件——头像截图上传插件的使用(带后台)

效果图:实现上传头像,右边是预览,有三个大小,可以对头像进行裁剪 ? HTML: toParentData 和 img 返回的是图片裁剪后的base64编码。其...

8915
来自专栏JackieZheng

探秘Tomcat——连接篇

  前两篇我们分别粗线条和细粒度的讲解了tomcat的服务是如何启动以及连接器Connector和容器Container又分别是如何被启动的.    本篇我们主...

2899
来自专栏西二旗一哥

iOS - autoreleasepool and @autoreleasepool

+ 在一个自动引用计数的环境中(并不是垃圾回收机制),一个包含了多个对象的 NSAutoreleasePool 对象能够接收 autorelease 消息并且...

1294
来自专栏Fish

CUDA C最佳实践-CUDA Best Practices(二)

9. 内存优化 看页数也知道,内存优化是性能提升最重要的途径。目标在于通过最大化带宽获得对硬件的最大使用率。最好使用快速内存而减少慢速内存的访问。这章就是各种讨...

28210
来自专栏潇涧技术专栏

Pury Project Analysis

Pury的源码:https://github.com/NikitaKozlov/Pury

822
来自专栏Android 研究

Android Handler机制3之SystemClock类

官网位置在https://developer.android.com/reference/android/os/SystemClock.html

1362

扫码关注云+社区