python技巧分享(五)

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

1 如何在命令行查看python文檔

  • 推薦方式
root@master:~$ pydoc sys.exit
Help on built-in function exit in sys:

sys.exit = exit(...)
    exit([status])

    Exit the interpreter by raising SystemExit(status).
    If the status is omitted or None, it defaults to zero (i.e., success).
    If the status is an integer, it will be used as the system exit status.
    If it is another kind of object, it will be printed and the system
    exit status will be one (i.e., failure).

root@master:~$ pydoc sorted
Help on built-in function sorted in module __builtin__:

sorted(...)
    sorted(iterable, cmp=None, key=None, reverse=False) --> new sorted list

第一個命令pydoc sys.exit查看sys模塊的exit函數文檔信息,第二個命令pydoc sorted查看了內建函數sorted的文檔信息。

2 如何將python代碼打包成獨立的二進制文件

  • 推薦方式

需要編譯的python代碼如下:

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

print 'hello, world!'

將python代碼打包成獨立的二進制文件步驟:

root@master:demo$ python hello_world.py
hello, world!
root@master:demo$ pip install pyinstaller
root@master:demo$ pyinstaller -F hello_world.py
root@master:demo$ cd ./dist/
root@master:dist$ ./hello_world
hello, world!

我解釋下上面命令行,首先使用python直接運行需要編譯成獨立二進制文件的hello_world.py,程序正常打印hello, world!,然後使用pip安裝pyinstaller,通過pyinstaller將hello_world.py打包成獨立的二進制文件,然後進入當前目錄下的dist目錄,運行打包成功的二進制文件hello_world,程序正常打印hello, world!。除了pyinstaller,還有其他工具可以實現類似功能,比如py2execx_Freeze,如果感興趣,可以看看。

3 如何自動格式化python代碼

  • 推薦方式

格式化前的demo.py代碼:

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

import math, sys;

def example1():
    ####This is a long comment. This should be wrapped to fit within 72 characters.
    some_tuple=(   1,2, 3,'a'  );
    some_variable={'long':'Long code lines should be wrapped within 79 characters.',
    'other':[math.pi, 100,200,300,9876543210,'This is a long string that goes on'],
    'more':{'inner':'This whole logical line should be wrapped.',some_tuple:[1,
    20,300,40000,500000000,60000000000000000]}}
    return (some_tuple, some_variable)
def example2(): return {'has_key() is deprecated':True}.has_key({'f':2}.has_key(''));
class Example3(   object ):
    def __init__    ( self, bar ):
     #Comments should have a space after the hash.
     if bar : bar+=1;  bar=bar* bar   ; return bar
     else:
                    some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
                    return (sys.path, some_string)

安裝autopep8,並使用autopep8格式化demo.py代碼:

root@master:demo$ pip install autopep8
root@master:demo$ autopep8 --in-place --aggressive --aggressive demo.py

格式化後的demo.py代碼:

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

import math
import sys


def example1():
    # This is a long comment. This should be wrapped to fit within 72
    # characters.
    some_tuple = (1, 2, 3, 'a')
    some_variable = {
        'long': 'Long code lines should be wrapped within 79 characters.',
        'other': [
            math.pi,
            100,
            200,
            300,
            9876543210,
            'This is a long string that goes on'],
        'more': {
            'inner': 'This whole logical line should be wrapped.',
            some_tuple: [
                1,
                20,
                300,
                40000,
                500000000,
                60000000000000000]}}
    return (some_tuple, some_variable)


def example2(): return ('' in {'f': 2}) in {'has_key() is deprecated': True};


class Example3(object):
    def __init__(self, bar):
        # Comments should have a space after the hash.
        if bar:
            bar += 1
            bar = bar * bar
            return bar
        else:
            some_string = """
                       Indentation in multiline strings should not be touched.
Only actual code should be reindented.
"""
            return (sys.path, some_string)

可以看到,經過autopep8格式化後的python代碼更易讀,也符合python的代碼風格,這裏的示例代碼使用autopep8官方例子,詳情請戳https://pypi.python.org/pypi/autopep8

發佈了63 篇原創文章 · 獲贊 11 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章