python常用模塊

OS 模塊

os模塊就是對操作系統進行操作,使用該模塊必須先導入模塊:

import os

getcwd() 獲取當前工作目錄(當前工作目錄默認都是當前文件所在的文件夾)

result = os.getcwd()
print(result)

chdir()改變當前工作目錄

os.chdir('/home/sy')
result = os.getcwd()
print(result)

操作時如果書寫完整的路徑則不需要考慮默認工作目錄的問題,按照實際書寫路徑操作

open('/home/sy/下載/02.txt','w')

listdir() 獲取指定文件夾中所有內容的名稱列表

result = os.listdir('/home/sy')
print(result)

mkdir() 創(chuàng)建文件夾

os.mkdir('girls')
os.mkdir('boys',0o777)

makedirs() 遞歸創(chuàng)建文件夾

os.makedirs('/home/sy/a/b/c/d')

rmdir() 刪除空目錄

os.rmdir('girls')

removedirs 遞歸刪除文件夾 必須都是空目錄

os.removedirs('/home/sy/a/b/c/d')

rename() 文件或文件夾重命名

os.rename('/home/sy/a','/home/sy/alibaba')
os.rename('02.txt','002.txt')

stat() 獲取文件或者文件夾的信息

result = os.stat('/home/sy/PycharmProject/Python3/10.27/01.py)
print(result)

system() 執(zhí)行系統命令(危險函數)

result = os.system('ls -al') #獲取隱藏文件

環(huán)境變量

環(huán)境變量就是一些命令的集合
操作系統的環(huán)境變量就是操作系統在執(zhí)行系統命令時搜索命令的目錄的集合
getenv() 獲取系統的環(huán)境變量
result = os.getenv('PATH')
print(result.split(':'))

pardir 表示上一層文件夾 ..表示上一層文件夾 不可省略!

print(os.pardir)

導入os模塊

import os

以下內容都是os.path子模塊中的內容

abspath() 將相對路徑轉化為絕對路徑

path = './boys'#相對
result = os.path.abspath(path)
print(result)

dirname() 獲取完整路徑當中的目錄部分 & basename()獲取完整路徑當中的主體部分

path = '/home/sy/boys'
result = os.path.dirname(path)
print(result)
result = os.path.basename(path)
print(result)

split() 將一個完整的路徑切割成目錄部分和主體部分

path = '/home/sy/boys'
result = os.path.split(path)
print(result)

join() 將2個路徑合并成一個

var1 = '/home/sy'
var2 = '000.py'
result = os.path.join(var1,var2)
print(result)

splitext() 將一個路徑切割成文件后綴和其他兩個部分,主要用于獲取文件的后綴

path = '/home/sy/000.py'
result = os.path.splitext(path)
print(result)

getsize() 獲取文件的大小

path = '/home/sy/000.py'
result = os.path.getsize(path)
print(result)

isfile() 檢測是否是文件

path = '/home/sy/000.py'
result = os.path.isfile(path)
print(result)

isdir() 檢測是否是文件夾

result = os.path.isdir(path)
print(result)

islink() 檢測是否是鏈接

path = '/initrd.img.old'
result = os.path.islink(path)
print(result)

常用命令

os.walk() 生成目錄樹下的所有文件名
os.chdir('dirname') 改變目錄
os.mkdir/makedirs('dirname')創(chuàng)建目錄/多層目錄
os.rmdir/removedirs('dirname') 刪除目錄/多層目錄
os.listdir('dirname') 列出指定目錄的文件
os.getcwd() 取得當前工作目錄
os.chmod() 改變目錄權限
os.path.basename(‘path/filename’) 去掉目錄路徑,返回文件名
os.path.dirname(‘path/filename’) 去掉文件名,返回目錄路徑
os.path.join(path1[,path2[,...]]) 將分離的各部分組合成一個路徑名
os.path.split('path') 返回( dirname(), basename())元組
os.path.splitext() 返回 (filename, extension) 元組
os.path.getatime\ctime\mtime 分別返回最近訪問、創(chuàng)建、修改時間
os.path.getsize() 返回文件大小
os.path.exists() 是否存在
os.path.isabs() 是否為絕對路徑
os.path.isdir() 是否為目錄
os.path.isfile() 是否為文件

sys 模塊

sys.argv 命令行參數List,第一個元素是程序本身路徑

time模塊

#! /usr/bin/env python
# -*- coding:utf-8 -*-
# __author__ = "TKQ"
import time
# 生成timestamp
time.time()
# 1477471508.05
#struct_time to timestamp
time.mktime(time.localtime())
#生成struct_time
# timestamp to struct_time 本地時間
time.localtime()
time.localtime(time.time())
# time.struct_time(tm_year=2016, tm_mon=10, tm_mday=26, tm_hour=16, tm_min=45, tm_sec=8, tm_wday=2, tm_yday=300, tm_isdst=0)
# timestamp to struct_time 格林威治時間
time.gmtime()
time.gmtime(time.time())
# time.struct_time(tm_year=2016, tm_mon=10, tm_mday=26, tm_hour=8, tm_min=45, tm_sec=8, tm_wday=2, tm_yday=300, tm_isdst=0)
#format_time to struct_time
time.strptime('2011-05-05 16:37:06', '%Y-%m-%d %X')
# time.struct_time(tm_year=2011, tm_mon=5, tm_mday=5, tm_hour=16, tm_min=37, tm_sec=6, tm_wday=3, tm_yday=125, tm_isdst=-1)
#生成format_time
#struct_time to format_time
time.strftime("%Y-%m-%d %X")
time.strftime("%Y-%m-%d %X",time.localtime())
#生成固定格式的時間表示格式
time.asctime(time.localtime())
time.ctime(time.time())

randmon(獲取隨機數)

random.random random.random()用于生成一個0到1的隨機符點數: 0 <= n < 1.0

random.uniform random.uniform(a, b),用于生成一個指定范圍內的隨機符點數,兩個參數其中一個是上限,一個是下限。如果a > b,則生成的隨機數n: a <= n <= b。如果 a <b, 則 b <= n <= a

代碼如下:

print random.uniform(10, 20)
print random.uniform(20, 10)
18.7356606526
12.5798298022 

random.randint random.randint(a, b),用于生成一個指定范圍內的整數。其中參數a是下限,參數b是上限,生成的隨機數n: a <= n <= b

代碼如下:

print random.randint(12, 20)  # 生成的隨機數 n: 12 <= n <= 20
print random.randint(20, 20)  # 結果永遠是20     
# print random.randint(20, 10)  # 該語句是錯誤的。下限必須小于上限

random.randrange random.randrange([start], stop[, step]),從指定范圍內,按指定基數遞增的集合中 獲取一個隨機數。如:random.randrange(10, 100, 2),結果相當于從[10, 12, 14, 16, ... 96, 98]序列中獲取一個隨機數。random.randrange(10, 100, 2)在結果上與 random.choice(range(10, 100, 2) 等效

random.choice random.choice從序列中獲取一個隨機元素。其函數原型為:random.choice(sequence)。參數sequence表示一個有序類型。這里要說明 一下:sequence在python不是一種特定的類型,而是泛指一系列的類型。list, tuple, 字符串都屬于sequence。有關sequence可以查看python手冊數據模型這一章。下面是使用choice的一些例子:

代碼如下:

print random.choice("學習Python")
print random.choice(["JGood", "is", "a", "handsome", "boy"])
print random.choice(("Tuple", "List", "Dict")) 

random.shuffle random.shuffle(x[, random]),用于將一個列表中的元素打亂。如:

代碼如下:

p = ["Python", "is", "powerful", "simple", "and so on..."]
random.shuffle(p)
print p
# ['powerful', 'simple', 'is', 'Python', 'and so on...'] 

random.sample random.sample(sequence, k),從指定序列中隨機獲取指定長度的片斷。sample函數不會修改原有序列

代碼如下:

list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
slice = random.sample(list, 5)  # 從list中隨機獲取5個元素,作為一個片斷返回
print slice
print list  # 原有序列并沒有改變

隨機整數:

代碼如下:

>>> import random
>>> random.randint(0,99)
# 21

隨機選取0到100間的偶數:

代碼如下:

>>> import random
>>> random.randrange(0, 101, 2)
# 42

隨機浮點數:

代碼如下:

>>> import random
>>> random.random()
0.85415370477785668
>>> random.uniform(1, 10)
# 5.4221167969800881

隨機字符:

代碼如下:

>>> import random
>>> random.choice('abcdefg&#%^*f')
# 'd'

多個字符中選取特定數量的字符:

代碼如下:

>>> import random
random.sample('abcdefghij', 3)
# ['a', 'd', 'b']

多個字符中選取特定數量的字符組成新字符串:

代碼如下:

>>> import random
>>> import string
>>> string.join( random.sample(['a','b','c','d','e','f','g','h','i','j'], 3) ).replace(" ","")
# 'fih'

隨機選取字符串:

代碼如下:

>>> import random
>>> random.choice ( ['apple', 'pear', 'peach', 'orange', 'lemon'] )
# 'lemon'

洗牌:

代碼如下:

>>> import random
>>> items = [1, 2, 3, 4, 5, 6]
>>> random.shuffle(items)
>>> items
# [3, 2, 5, 6, 4, 1]

numpy模塊

numpy元素的屬性

numpy的所有值都有以下幾個屬性

A = np.arange(12).reshape(3, 4).astype(np.float32)

print(A.ndim)
print(A.shape)
print(A.size)
print(A.dtype)
print(A.itemsize)

# 輸出結果為
# 2
# (3, 4)
# 12
# float32
# 4

A.ndim
數組軸的個數,在python的世界中,軸的個數被稱作秩

A.shape
數組的維度。

A.size
數組元素的總個數。

A.dtype
元素的數據類型。

A.itemsize
數組中每個元素的字節(jié)大小。

生成數列

指定值的增量

data = np.arange(10, 30, 5)
print(data)  # [10 15 20 25]

指定值的個數

data = np.linspace(1, 10, 5)
print(data) # [  1\.     3.25   5.5    7.75  10\.  ]

生成矩陣

data = np.array([[2, 3, 4], [4, 5, 6]], dtype=np.float32)
print(data)
# [[ 2\.  3\.  4.]
#  [ 4\.  5\.  6.]]

生成全是0的矩陣

data = np.zeros((3, 4))
print(data)
# [[ 0\.  0\.  0\.  0.]
#  [ 0\.  0\.  0\.  0.]
#  [ 0\.  0\.  0\.  0.]]

生成全是1的矩陣

data = np.ones((3, 4))
print(data)
# [[ 1\.  1\.  1\.  1.]
#  [ 1\.  1\.  1\.  1.]
#  [ 1\.  1\.  1\.  1.]]

生成隨機數據

隨機生成0~1之間的數

data = np.random.random()
print(data) #0.01447623686510957

隨機生成指定范圍內的浮點數

data = np.random.uniform(10,20)
print(data)
# 14.646829941471552

隨機整數

data = np.random.randint(10,20)
print(data)
# 17

隨機生成一個矩陣

data = np.random.random((3,4))
print(data)
# [[ 0.77829489  0.63959774  0.83723733  0.95292845]
#  [ 0.78949057  0.38655045  0.79205805  0.06847395]
#  [ 0.5284635   0.95181041  0.39267602  0.23638718]]

多維矩陣

data = np.random.random((2,3,4))
print(data)
# [[[ 0.36605927  0.47719931  0.16654015  0.17585629]
#   [ 0.66085507  0.09883734  0.22603851  0.91388161]
#   [ 0.33416014  0.82187631  0.91063299  0.25781208]]
# 
#  [[ 0.56585862  0.09606677  0.84916434  0.26007262]
#   [ 0.16145394  0.61120144  0.75447741  0.40179179]
#   [ 0.55887648  0.45416114  0.17644248  0.43142769]]]

合并

A = np.array([1, 1, 1])
B = np.array([2, 2, 2])
#縱向合并
print(np.vstack((A, B)))
#橫向合并
print(np.hstack((A, B)))
# [[1 1 1]
#  [2 2 2]]
#
# [1 1 1 2 2 2]

增加維度

添加一個橫向的維度

A = np.array([1, 1, 1])
B = A[np.newaxis, :]
print(A.shape)
print(B.shape)
print(B)
# (3,)
# (1, 3)
# [[1 1 1]]

添加一個縱向的維度

A = np.array([1, 1, 1])
B = A[:,np.newaxis]
print(A.shape)
print(B.shape)
print(B)
# (3,)
# (3, 1)
# [[1]
#  [1]
#  [1]]

分割

A = np.arange(12).reshape(3, 4)
print(A)
#橫向分割
print(np.vsplit(A, 3))
#縱向分割
print(np.hsplit(A, 2))
#可以在參數中指定分割哪個坐標
print(np.split(A, 3, axis=0))
print(np.split(A, 2, axis=1))
#不等量分割
print(np.array_split(A, 3, axis=1))

深層拷貝

在numpy中直接用"="號賦值,相當于賦予的是指針,賦值前后的"兩個"變量是同"一個"變量.比如,下面的變量a,b,改變a,b也會跟著變化.

a = np.array([1, 2, 3])
b = a
a[0] = 666
print(a)
print(b)
#[666   2   3]
#[666   2   3]

如果想要兩個變量不關聯,需要這樣拷貝

b = a.copy()

運算

numpy中矩陣的加法減法的運算和普通的加減運算相同,但是矩陣乘法的運算需要用dot函數,如下

A = np.array([[2, 3],
              [4, 7]])
B = np.array([[1, 2],
              [3, 4]])
print(A + B)
print(A - B)
print(np.dot(A, B))

# [[ 3  5]
#  [ 7 11]]
#
# [[1 1]
#  [1 3]]
#
# [[11 16]
#  [25 36]]

索引與切片

numpy中的索引與切片功能比python中的切片更加強大

索引多維數組

data = np.random.random((3,4,5))
print(data[0,2,3])

image

索引多維數組的時候也可以用切片

data = np.random.random((3,4,5))
print(data[1,:,3])
print(data[:2,:,3])

argparse模塊

argparse是一個完整的參數處理庫。參數可以根據add_argument()的action選項觸發(fā)不同action。支持的action有存儲參數(單個,或作為列表的一部分);存儲常量的值(對布爾開關true/false有特殊處理)。默認動作是存儲參數值。支持type(指定存儲類型)和dest(指定存儲變量)等參數。

然后使用函數parse_args()進行參數解析,這個函數的輸入默認是sys.argv[1:],也可以使用其他字符串列表。選項使用GNU/POSIX語法處理,可以混合選項和參數值。parse_args的返回值是一個包含命令參數的Namespace。所有參數以屬性的形式存在,比如args.myoption。

下面是一個簡單的示例:argparse_short.py


import argparse

parser = argparse.ArgumentParser(description='Short sample app')

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print(parser.parse_args(['-a', '-bval', '-c', '3']))

執(zhí)行結果:


$ python3 argparse_short.py
Namespace(a=True, b='val', c=3)

長參數argparse_long.py


import argparse

parser = argparse.ArgumentParser(
    description='Example with long option names',
)

parser.add_argument('--noarg', action="store_true",
                    default=False)
parser.add_argument('--witharg', action="store",
                    dest="witharg")
parser.add_argument('--witharg2', action="store",
                    dest="witharg2", type=int)

print(
    parser.parse_args(
        ['--noarg', '--witharg', 'val', '--witharg2=3']
    )
)

執(zhí)行結果


$ python3 argparse_long.py

Namespace(noarg=True, witharg='val', witharg2=3)

混合可選和必選參數:argparse_arguments.py


import argparse

parser = argparse.ArgumentParser(
    description='Example with nonoptional arguments',
)

parser.add_argument('count', action="store", type=int)
parser.add_argument('units', action="store")

print(parser.parse_args())

執(zhí)行結果


$ python3 argparse_arguments.py 3 inches

Namespace(count=3, units='inches')

$ python3 argparse_arguments.py some inches

usage: argparse_arguments.py [-h] count units
argparse_arguments.py: error: argument count: invalid int value:
'some'

$ python3 argparse_arguments.py

usage: argparse_arguments.py [-h] count units
argparse_arguments.py: error: the following arguments are
required: count, units

參數action有:

store:默認action模式,存儲值到指定變量。
store_const:存儲值在參數的const部分指定,多用于實現非布爾的命令行flag。
store_true / store_false:布爾開關??梢?個參數對應一個變量。
append:存儲值到列表,該參數可以重復使用。
append_const:存儲值到列表,存儲值在參數的const部分指定。
version 輸出版本信息然后退出。

下面是各種action的示例:argparse_action.py


import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-s', action='store',
                    dest='simple_value',
                    help='Store a simple value')

parser.add_argument('-c', action='store_const',
                    dest='constant_value',
                    const='value-to-store',
                    help='Store a constant value')

parser.add_argument('-t', action='store_true',
                    default=False,
                    dest='boolean_t',
                    help='Set a switch to true')
parser.add_argument('-f', action='store_false',
                    default=True,
                    dest='boolean_f',
                    help='Set a switch to false')

parser.add_argument('-a', action='append',
                    dest='collection',
                    default=[],
                    help='Add repeated values to a list')

parser.add_argument('-A', action='append_const',
                    dest='const_collection',
                    const='value-1-to-append',
                    default=[],
                    help='Add different values to list')
parser.add_argument('-B', action='append_const',
                    dest='const_collection',
                    const='value-2-to-append',
                    help='Add different values to list')

parser.add_argument('--version', action='version',
                    version='%(prog)s 1.0')

results = parser.parse_args()
print('simple_value     = {!r}'.format(results.simple_value))
print('constant_value   = {!r}'.format(results.constant_value))
print('boolean_t        = {!r}'.format(results.boolean_t))
print('boolean_f        = {!r}'.format(results.boolean_f))
print('collection       = {!r}'.format(results.collection))
print('const_collection = {!r}'.format(results.const_collection))

執(zhí)行結果如下,注意'simple_value'等被自動化轉化為大寫


$ python3 argparse_action.py -h

usage: argparse_action.py [-h] [-s SIMPLE_VALUE] [-c] [-t] [-f]
                          [-a COLLECTION] [-A] [-B] [--version]

optional arguments:
  -h, --help       show this help message and exit
  -s SIMPLE_VALUE  Store a simple value
  -c               Store a constant value
  -t               Set a switch to true
  -f               Set a switch to false
  -a COLLECTION    Add repeated values to a list
  -A               Add different values to list
  -B               Add different values to list
  --version        show program's version number and exit

$ python3 argparse_action.py -s value

simple_value     = 'value'
constant_value   = None
boolean_t        = False
boolean_f        = True
collection       = []
const_collection = []

$ python3 argparse_action.py -c

simple_value     = None
constant_value   = 'value-to-store'
boolean_t        = False
boolean_f        = True
collection       = []
const_collection = []

$ python3 argparse_action.py -t

simple_value     = None
constant_value   = None
boolean_t        = True
boolean_f        = True
collection       = []
const_collection = []

$ python3 argparse_action.py -f

simple_value     = None
constant_value   = None
boolean_t        = False
boolean_f        = False
collection       = []
const_collection = []

$ python3 argparse_action.py -a one -a two -a three

simple_value     = None
constant_value   = None
boolean_t        = False
boolean_f        = True
collection       = ['one', 'two', 'three']
const_collection = []

$ python3 argparse_action.py -B -A

simple_value     = None
constant_value   = None
boolean_t        = False
boolean_f        = True
collection       = []
const_collection = ['value-2-to-append', 'value-1-to-append']

$ python3 argparse_action.py --version

argparse_action.py 1.0

可選前綴

ArgumentParser函數中的選項prefix_chars可以指定前綴。默認使用UNIX風格,命令行使用‘-’作為前綴。可以使用windows的’/’或者其他符號。

argparse_prefix_chars.py


import argparse

parser = argparse.ArgumentParser(
    description='Change the option prefix characters',
    prefix_chars='-+/',
)

parser.add_argument('-a', action="store_false",
                    default=None,
                    help='Turn A off',
                    )
parser.add_argument('+a', action="store_true",
                    default=None,
                    help='Turn A on',
                    )
parser.add_argument('//noarg', '++noarg',
                    action="store_true",
                    default=False)

print(parser.parse_args())

執(zhí)行結果


$ python3 argparse_prefix_chars.py -h

usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg]

Change the option prefix characters

optional arguments:
  -h, --help        show this help message and exit
  -a                Turn A off
  +a                Turn A on
  //noarg, ++noarg

$ python3 argparse_prefix_chars.py +a

Namespace(a=True, noarg=False)

$ python3 argparse_prefix_chars.py -a

Namespace(a=False, noarg=False)

$ python3 argparse_prefix_chars.py //noarg

Namespace(a=None, noarg=True)

$ python3 argparse_prefix_chars.py ++noarg

Namespace(a=None, noarg=True)

$ python3 argparse_prefix_chars.py --noarg

usage: argparse_prefix_chars.py [-h] [-a] [+a] [//noarg]
argparse_prefix_chars.py: error: unrecognized arguments: --noarg

處理配置文件中的參數

argparse_with_shlex.py


import argparse
from configparser import ConfigParser
import shlex

parser = argparse.ArgumentParser(description='Short sample app')

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

config = ConfigParser()
config.read('argparse_with_shlex.ini')
config_value = config.get('cli', 'options')
print('Config  :', config_value)

argument_list = shlex.split(config_value)
print('Arg List:', argument_list)

print('Results :', parser.parse_args(argument_list))

其中argparse_with_shlex.ini文件的內容如下:


[cli]
options = -a -b 2

執(zhí)行結果


$ python3 argparse_with_shlex.py

Config  : -a -b 2
Arg List: ['-a', '-b', '2']
Results : Namespace(a=True, b='2', c=None)

上面例子使用了ConfigParser來讀取配置,再用shlex來切割參數。也可以通過fromfile_prefix_chars 告知argparse輸入參數為文件。

argparse_fromfile_prefix_chars.py


import argparse
import shlex

parser = argparse.ArgumentParser(description='Short sample app',
                                 fromfile_prefix_chars='@',
                                 )

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print(parser.parse_args(['@argparse_fromfile_prefix_chars.txt']))

argparse_fromfile_prefix_chars.txt


-a
-b
2

執(zhí)行結果


$ python3 argparse_fromfile_prefix_chars.py

Namespace(a=True, b='2', c=None)

幫助

  • 自動生成

Argparse會自動生成的幫助和版本信息。ArgumentParser的add_help參數控制幫助的生成,默認是開啟。

argparse_with_help.py


import argparse

parser = argparse.ArgumentParser(add_help=True)

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print(parser.parse_args())

下例就關閉幫助:

argparse_without_help.py


import argparse

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print(parser.parse_args())

執(zhí)行結果


$ python argparse_with_help.py -h
usage: argparse_with_help.py [-h] [-a] [-b B] [-c C]
optional arguments:
-h, --help show this help message and exit
-a
-b B
-c C
$ python argparse_without_help.py -h
usage: argparse_without_help.py [-a] [-b B] [-c C]
argparse_without_help.py: error: unrecognized arguments: -h

  • 自定義幫助

argparse_custom_help.py


import argparse

parser = argparse.ArgumentParser(add_help=True)

parser.add_argument('-a', action="store_true", default=False)
parser.add_argument('-b', action="store", dest="b")
parser.add_argument('-c', action="store", dest="c", type=int)

print('print_usage output:')
parser.print_usage()
print()

print('print_help output:')
parser.print_help()

執(zhí)行結果


$ python3 argparse_custom_help.py

print_usage output:
usage: argparse_custom_help.py [-h] [-a] [-b B] [-c C]

print_help output:
usage: argparse_custom_help.py [-h] [-a] [-b B] [-c C]

optional arguments:
  -h, --help  show this help message and exit
  -a
  -b B
  -c C

argparse_raw_description_help_formatter.py


import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.RawDescriptionHelpFormatter,
    description="""
    description
        not
           wrapped""",
    epilog="""
    epilog
      not
         wrapped""",
)

parser.add_argument(
    '-a', action="store_true",
    help="""argument
    help is
    wrapped
    """,
)

parser.print_help()

執(zhí)行結果


$ python3 argparse_raw_description_help_formatter.py

usage: argparse_raw_description_help_formatter.py [-h] [-a]

    description
        not
           wrapped

optional arguments:
  -h, --help  show this help message and exit
  -a          argument help is wrapped

    epilog
      not
         wrapped

argparse_raw_text_help_formatter.py


import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.RawTextHelpFormatter,
    description="""
    description
        not
           wrapped""",
    epilog="""
    epilog
      not
         wrapped""",
)

parser.add_argument(
    '-a', action="store_true",
    help="""argument
    help is not
    wrapped
    """,
)

parser.print_help()

執(zhí)行結果


$ python3 argparse_raw_text_help_formatter.py

usage: argparse_raw_text_help_formatter.py [-h] [-a]

    description
        not
           wrapped

optional arguments:
  -h, --help  show this help message and exit
  -a          argument
                  help is not
                  wrapped

    epilog
      not
         wrapped

argparse_metavar_type_help_formatter.py


import argparse

parser = argparse.ArgumentParser(
    add_help=True,
    formatter_class=argparse.MetavarTypeHelpFormatter,
)

parser.add_argument('-i', type=int, dest='notshown1')
parser.add_argument('-f', type=float, dest='notshown2')

parser.print_help()

執(zhí)行結果


$ python3 argparse_metavar_type_help_formatter.py

usage: argparse_metavar_type_help_formatter.py [-h] [-i int] [-f
 float]

optional arguments:
  -h, --help  show this help message and exit
  -i int
  -f float

組織解析器

公共解析器:通過父子類來實現。

見argparse_parent_base.py:


import argparse

parser = argparse.ArgumentParser(add_help=False)

parser.add_argument('--user', action="store")
parser.add_argument('--password', action="store")

argparse_uses_parent.py


import argparse
import argparse_parent_base

parser = argparse.ArgumentParser(
    parents=[argparse_parent_base.parser],
)

parser.add_argument('--local-arg',
                    action="store_true",
                    default=False)

print(parser.parse_args())

注意:父類關閉了help。子類卻默認開啟了help。執(zhí)行結果:


$ python3 argparse_uses_parent.py -h

usage: argparse_uses_parent.py [-h] [--user USER]
                               [--password PASSWORD]
                               [--local-arg]

optional arguments:
  -h, --help           show this help message and exit
  --user USER
  --password PASSWORD
  --local-arg

參數沖突

argparse_conflict_handler_resolve.py


import argparse

parser = argparse.ArgumentParser(conflict_handler='resolve')

parser.add_argument('-a', action="store")
parser.add_argument('-b', action="store", help='Short alone')
parser.add_argument('--long-b', '-b',
                    action="store",
                    help='Long and short together')

print(parser.parse_args(['-h']))

執(zhí)行結果


$ python3 argparse_conflict_handler_resolve.py

usage: argparse_conflict_handler_resolve.py [-h] [-a A]
[--long-b LONG_B]

optional arguments:
  -h, --help            show this help message and exit
  -a A
  --long-b LONG_B, -b LONG_B
                        Long and short together

argparse_conflict_handler_resolve2.py、


import argparse

parser = argparse.ArgumentParser(conflict_handler='resolve')

parser.add_argument('-a', action="store")
parser.add_argument('--long-b', '-b',
                    action="store",
                    help='Long and short together')
parser.add_argument('-b', action="store", help='Short alone')

print(parser.parse_args(['-h']))

執(zhí)行結果


$ python3 argparse_conflict_handler_resolve2.py

usage: argparse_conflict_handler_resolve2.py [-h] [-a A]
                                             [--long-b LONG_B]
                                             [-b B]

optional arguments:
  -h, --help       show this help message and exit
  -a A
  --long-b LONG_B  Long and short together
  -b B             Short alone

參數分組

默認有可選參數和必選參數組。

argparse_default_grouping.py


import argparse

parser = argparse.ArgumentParser(description='Short sample app')

parser.add_argument('--optional', action="store_true",
                    default=False)
parser.add_argument('positional', action="store")

print(parser.parse_args())

執(zhí)行結果


$ python3 argparse_default_grouping.py -h

usage: argparse_default_grouping.py [-h] [--optional] positional

Short sample app

positional arguments:
  positional

optional arguments:
  -h, --help  show this help message and exit
  --optional

前面的用戶名和密碼就可以分組:

argparse_parent_with_group.py


import argparse

parser = argparse.ArgumentParser(add_help=False)

group = parser.add_argument_group('authentication')

group.add_argument('--user', action="store")
group.add_argument('--password', action="store")

argparse_uses_parent_with_group.py


import argparse
import argparse_parent_with_group

parser = argparse.ArgumentParser(
    parents=[argparse_parent_with_group.parser],
)

parser.add_argument('--local-arg',
                    action="store_true",
                    default=False)

print(parser.parse_args())

執(zhí)行結果


$ python3 argparse_uses_parent_with_group.py -h

usage: argparse_uses_parent_with_group.py [-h] [--user USER]
                                          [--password PASSWORD]
                                          [--local-arg]

optional arguments:
  -h, --help           show this help message and exit
  --local-arg

authentication:
  --user USER
  --password PASSWORD

互斥選項

使用add_mutually_exclusive_group()可以添加互斥選項:

argparse_mutually_exclusive.py


import argparse

parser = argparse.ArgumentParser()

group = parser.add_mutually_exclusive_group()
group.add_argument('-a', action='store_true')
group.add_argument('-b', action='store_true')

print(parser.parse_args())

執(zhí)行結果


$ python3 argparse_mutually_exclusive.py -h

usage: argparse_mutually_exclusive.py [-h] [-a | -b]

optional arguments:
  -h, --help  show this help message and exit
  -a
  -b

$ python3 argparse_mutually_exclusive.py -a

Namespace(a=True, b=False)

$ python3 argparse_mutually_exclusive.py -b

Namespace(a=False, b=True)

$ python3 argparse_mutually_exclusive.py -a -b

usage: argparse_mutually_exclusive.py [-h] [-a | -b]
argparse_mutually_exclusive.py: error: argument -b: not allowed
with argument -a

嵌套解析

argparse_subparsers.py


import argparse

parser = argparse.ArgumentParser()

subparsers = parser.add_subparsers(help='commands')

# A list command
list_parser = subparsers.add_parser(
    'list', help='List contents')
list_parser.add_argument(
    'dirname', action='store',
    help='Directory to list')

# A create command
create_parser = subparsers.add_parser(
    'create', help='Create a directory')
create_parser.add_argument(
    'dirname', action='store',
    help='New directory to create')
create_parser.add_argument(
    '--read-only', default=False, action='store_true',
    help='Set permissions to prevent writing to the directory',
)

# A delete command
delete_parser = subparsers.add_parser(
    'delete', help='Remove a directory')
delete_parser.add_argument(
    'dirname', action='store', help='The directory to remove')
delete_parser.add_argument(
    '--recursive', '-r', default=False, action='store_true',
    help='Remove the contents of the directory, too',
)

print(parser.parse_args())

執(zhí)行結果


$ python3 argparse_subparsers.py -h

usage: argparse_subparsers.py [-h] {list,create,delete} ...

positional arguments:
  {list,create,delete}  commands
    list                List contents
    create              Create a directory
    delete              Remove a directory

optional arguments:
  -h, --help            show this help message and exit

$ python3 argparse_subparsers.py create -h

usage: argparse_subparsers.py create [-h] [--read-only] dirname

positional arguments:
  dirname      New directory to create

optional arguments:
  -h, --help   show this help message and exit
  --read-only  Set permissions to prevent writing to the directo
ry

$ python3 argparse_subparsers.py delete -r foo

Namespace(dirname='foo', recursive=True)

高級參數處理

可變參數:數字N代表N的參數,?0或者1個參數。*0或者多個參數。+1或者多個參數。

argparse_nargs.py


import argparse

parser = argparse.ArgumentParser()

parser.add_argument('--three', nargs=3)
parser.add_argument('--optional', nargs='?')
parser.add_argument('--all', nargs='*', dest='all')
parser.add_argument('--one-or-more', nargs='+')

print(parser.parse_args())

執(zhí)行結果


$ python3 argparse_nargs.py -h

usage: argparse_nargs.py [-h] [--three THREE THREE THREE]
                [--optional [OPTIONAL]]
                [--all [ALL [ALL ...]]]
                [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]]

optional arguments:
  -h, --help            show this help message and exit
  --three THREE THREE THREE
  --optional [OPTIONAL]
  --all [ALL [ALL ...]]
  --one-or-more ONE_OR_MORE [ONE_OR_MORE ...]

$ python3 argparse_nargs.py

Namespace(all=None, one_or_more=None, optional=None, three=None)

$ python3 argparse_nargs.py --three

usage: argparse_nargs.py [-h] [--three THREE THREE THREE]
                [--optional [OPTIONAL]]
                [--all [ALL [ALL ...]]]
                [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]]
argparse_nargs.py: error: argument --three: expected 3
argument(s)

$ python3 argparse_nargs.py --three a b c

Namespace(all=None, one_or_more=None, optional=None,
three=['a', 'b', 'c'])

$ python3 argparse_nargs.py --optional

Namespace(all=None, one_or_more=None, optional=None, three=None)

$ python3 argparse_nargs.py --optional with_value

Namespace(all=None, one_or_more=None, optional='with_value',
three=None)

$ python3 argparse_nargs.py --all with multiple values

Namespace(all=['with', 'multiple', 'values'], one_or_more=None,
optional=None, three=None)

$ python3 argparse_nargs.py --one-or-more with_value

Namespace(all=None, one_or_more=['with_value'], optional=None,
three=None)

$ python3 argparse_nargs.py --one-or-more with multiple values

Namespace(all=None, one_or_more=['with', 'multiple', 'values'],
optional=None, three=None)

$ python3 argparse_nargs.py --one-or-more

usage: argparse_nargs.py [-h] [--three THREE THREE THREE]
                [--optional [OPTIONAL]]
                [--all [ALL [ALL ...]]]
                [--one-or-more ONE_OR_MORE [ONE_OR_MORE ...]]
argparse_nargs.py: error: argument --one-or-more: expected
at least one argument

參數類型

argparse_type.py


import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-i', type=int)
parser.add_argument('-f', type=float)
parser.add_argument('--file', type=open)

try:
    print(parser.parse_args())

except IOError as msg:
    parser.error(str(msg))

執(zhí)行結果


$ python3 argparse_type.py -i 1

Namespace(f=None, file=None, i=1)

$ python3 argparse_type.py -f 3.14

Namespace(f=3.14, file=None, i=None)

$ python3 argparse_type.py --file argparse_type.py

Namespace(f=None, file=<_io.TextIOWrapper
name='argparse_type.py' mode='r' encoding='UTF-8'>, i=None)

$ python3 argparse_type.py -i a

usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE]
argparse_type.py: error: argument -i: invalid int value: 'a'

$ python3 argparse_type.py -f 3.14.15

usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE]
argparse_type.py: error: argument -f: invalid float value:
'3.14.15'

$ python3 argparse_type.py --file does_not_exist.txt

usage: argparse_type.py [-h] [-i I] [-f F] [--file FILE]
argparse_type.py: error: [Errno 2] No such file or directory:
'does_not_exist.txt'

Choices可以指定參數的選項:

argparse_choices.py


import argparse

parser = argparse.ArgumentParser()

parser.add_argument(
    '--mode',
    choices=('read-only', 'read-write'),
)

print(parser.parse_args())

執(zhí)行結果


$ python3 argparse_choices.py -h

usage: argparse_choices.py [-h] [--mode {read-only,read-write}]

optional arguments:
  -h, --help            show this help message and exit
  --mode {read-only,read-write}

$ python3 argparse_choices.py --mode read-only

Namespace(mode='read-only')

$ python3 argparse_choices.py --mode invalid

usage: argparse_choices.py [-h] [--mode {read-only,read-write}]
argparse_choices.py: error: argument --mode: invalid choice:
'invalid' (choose from 'read-only', 'read-write')

文件參數

argparse_FileType.py


import argparse

parser = argparse.ArgumentParser()

parser.add_argument('-i', metavar='in-file',
                    type=argparse.FileType('rt'))
parser.add_argument('-o', metavar='out-file',
                    type=argparse.FileType('wt'))

try:
    results = parser.parse_args()
    print('Input file:', results.i)
    print('Output file:', results.o)
except IOError as msg:
    parser.error(str(msg))

執(zhí)行結果


$ python3 argparse_FileType.py -h

usage: argparse_FileType.py [-h] [-i in-file] [-o out-file]

optional arguments:
  -h, --help   show this help message and exit
  -i in-file
  -o out-file

$ python3 argparse_FileType.py -i argparse_FileType.py -o tmp_\
file.txt

Input file: <_io.TextIOWrapper name='argparse_FileType.py'
mode='rt' encoding='UTF-8'>
Output file: <_io.TextIOWrapper name='tmp_file.txt' mode='wt'
encoding='UTF-8'>

$ python3 argparse_FileType.py -i no_such_file.txt

usage: argparse_FileType.py [-h] [-i in-file] [-o out-file]
argparse_FileType.py: error: argument -i: can't open
'no_such_file.txt': [Errno 2] No such file or directory:
'no_such_file.txt'

自定義action

自定義action是argparse.Action的子類可以處理add_argument中的參數定義相關的參數,并返回一個可調用對象。構造函數會處理參數定義,僅僅需要處理call函數。call函數中parser代表解釋器,namespace用于返回解釋結果,value為要處理的參數,option_string用于觸發(fā)action(對可選參數,永遠是None。

argparse_custom_action.py


import argparse

class CustomAction(argparse.Action):
    def __init__(self,
                 option_strings,
                 dest,
                 nargs=None,
                 const=None,
                 default=None,
                 type=None,
                 choices=None,
                 required=False,
                 help=None,
                 metavar=None):
        argparse.Action.__init__(self,
                                 option_strings=option_strings,
                                 dest=dest,
                                 nargs=nargs,
                                 const=const,
                                 default=default,
                                 type=type,
                                 choices=choices,
                                 required=required,
                                 help=help,
                                 metavar=metavar,
                                 )
        print('Initializing CustomAction')
        for name, value in sorted(locals().items()):
            if name == 'self' or value is None:
                continue
            print('  {} = {!r}'.format(name, value))
        print()
        return

    def __call__(self, parser, namespace, values,
                 option_string=None):
        print('Processing CustomAction for {}'.format(self.dest))
        print('  parser = {}'.format(id(parser)))
        print('  values = {!r}'.format(values))
        print('  option_string = {!r}'.format(option_string))

        # Do some arbitrary processing of the input values
        if isinstance(values, list):
            values = [v.upper() for v in values]
        else:
            values = values.upper()
        # Save the results in the namespace using the destination
        # variable given to our constructor.
        setattr(namespace, self.dest, values)
        print()

parser = argparse.ArgumentParser()

parser.add_argument('-a', action=CustomAction)
parser.add_argument('-m', nargs='*', action=CustomAction)

results = parser.parse_args(['-a', 'value',
                             '-m', 'multivalue',
                             'second'])
print(results)

執(zhí)行結果


$ python3 argparse_custom_action.py

Initializing CustomAction
  dest = 'a'
  option_strings = ['-a']
  required = False

Initializing CustomAction
  dest = 'm'
  nargs = '*'
  option_strings = ['-m']
  required = False

Processing CustomAction for a
  parser = 4315836992
  values = 'value'
  option_string = '-a'

Processing CustomAction for m
  parser = 4315836992
  values = ['multivalue', 'second']
  option_string = '-m'

Namespace(a='VALUE', m=['MULTIVALUE', 'SECOND'])

當然,還有其他的常用模塊,比如numpy,pandas等,歡迎各位道友補充

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

相關閱讀更多精彩內容

  • 常用模塊 認識模塊 什么是模塊 什么是模塊? 常見的場景:一個模塊就是一個包含了python定義和聲明的文件,文...
    go以恒閱讀 2,171評論 0 6
  • 1.python2中保存在內存中的代碼內容編碼格式都是其本身的編碼 類型,而python3中都會被轉換為unico...
    飛鳥在籠閱讀 1,377評論 0 1
  • collections模塊 在內置數據類型(dict、list、set、tuple)的基礎上,collection...
    可笑的黑耀斑閱讀 876評論 0 1
  • 練習題 1.logging模塊有幾個日志級別? logging的日志可以分為debug(), info(), wa...
    飛鳥在籠閱讀 1,413評論 0 1
  • Time 模塊 時間模塊常用的有如下幾種。 元組形式顯示時間: UTC時間: 將格式化的時間轉換為元組形式的時間:...
    斷尾壁虎V閱讀 515評論 0 1

友情鏈接更多精彩內容