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。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    小邁克閱讀 3,124評論 1 3
  • 本節(jié)內容 Python介紹 發(fā)展史 Python 2 or 3? 安裝 Hello World程序 變量 用戶輸入...
    小小不懂11閱讀 3,542評論 2 30
  • # Python 資源大全中文版 我想很多程序員應該記得 GitHub 上有一個 Awesome - XXX 系列...
    aimaile閱讀 26,835評論 6 427
  • 一個故事,或許可以來源歷史。但也可以埋沒于歷史。 東漢末年,漢王朝走向滅亡。群雄并起,豪強割據。下邳太守--楚寇也...
    我是格嚕特閱讀 265評論 0 0
  • 1 長年在外打拼的表哥,突然帶著表嫂上我家來了。一落座,表哥就劈頭蓋臉向我“控訴”表嫂的“罪狀”:你看看她,像不像...
    黔小蠻閱讀 1,764評論 0 3

友情鏈接更多精彩內容