python3:系統管理模塊,字符串詳解

shutil模塊

用於執行與文件系統相關的命令

>>> import shutil
>>> f1 = open('/bin/ls', 'rb')
>>> f2 = open('/tmp/list3', 'wb')
>>> shutil.copyfileobj(f1, f2)
>>> f1.close()
>>> f2.close()

>>> shutil.copy('/etc/hosts', '/tmp/zhuji')  # cp /etc/hosts /tmp/zhuji
'/tmp/zhuji'

>>> shutil.copy2('/etc/hosts', '/tmp/zhuji2')  # cp -p /etc/hosts /tmp/zhuji2
'/tmp/zhuji2'

>>> shutil.copytree('/etc/security', '/tmp/security')  # cp -r
'/tmp/security'

>>> shutil.move('/tmp/security', '/var/tmp/anquan')  # mv
'/var/tmp/anquan'

>>> shutil.rmtree('/var/tmp/anquan')  # rm -rf

>>> shutil.chown('/tmp/zhuji', user='student', group='student')  # chown

# 查看幫助
>>> help(shutil)
>>> help(shutil.chown)
# 官方文檔:https://docs.python.org/zh-cn/3/library/index.html

subprocess模塊

用於執行系統命令

# 只要記住以下形式即可
>>> import subprocess
>>> result = subprocess.run('ls ~', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# 'ls ~'  -> 要執行的命令
# shell=True   -> 在shell環境中運行命令
# stdout=subprocess.PIPE  -> 固定寫法,用於將輸出保存到stdout中
# stderr=subprocess.PIPE  -> 固定寫法,用於將錯誤保存到stderr中
>>> result  # 可以看到result的各種屬性
>>> result.args
'ls ~'
>>> result.returncode   # 返回值,即$?
0
>>> result.stdout.decode()  # stdout是bytes類型,轉爲str類型
>>> result.stderr.decode()  # stderr是bytes類型,轉爲str類型

>>> result = subprocess.run('id tom', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
>>> result.returncode
1
>>> result.stderr.decode()
'id: tom: no such user\n'

python語法風格

# 鏈式多重賦值
>>> x = y = 10
>>> id(x)  # 查看變量在內存中的地址
9360736
>>> id(y)
9360736

>>> l1 = l2 = [1, 2, 3]
>>> id(l1)
140338008994056
>>> id(l2)
140338008994056
>>> l1
[1, 2, 3]
>>> l2
[1, 2, 3]
>>> l2.append(10)
>>> l2
[1, 2, 3, 10]
>>> l1
[1, 2, 3, 10]

# 多元賦值
>>> a, b = 1, 2
>>> c, d = 'mn'
>>> d, f = (100, 200)
>>> g, h = ['tom', 'jerry']
>>> a, b = b, a   # 兩個變量的值互換
>>> a
1
>>> b
2

關鍵字

爲了實現python的語法,它保留了一些名字,不能被替換

>>> import keyword
>>> keyword.kwlist
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

內建

內建不是關鍵字,可以被覆蓋,但是儘量不要覆蓋。

>>> len
<built-in function len>
>>> len('abcd')
4
>>> len = 100
>>> len('abcd')  # 報錯,因爲此時len不再是函數,而是數字100
# https://docs.python.org/zh-cn/3/library/functions.html

python模塊佈局

#!/usr/local/bin/python3         # 解釋器位置
"文檔字符串,用於help"

import string                    # 導入模塊
import shutil

all_chs = string.ascii_letters + string.digits   # 全局變量定義
debug = True

class MyClass:                    # 定義類
    pass

def my_func():                    # 定義函數
    pass

if __name__ == '__main__':
    mc = MyClass()
    my_func()

編程思路

  1. 發呆。思考程的工作方式,交互式?非交互?
[root@localhost day04]# python3 mkfile.py
文件名: /etc/hosts
文件已存在,請重試。
文件名: /
文件已存在,請重試。
文件名: /tmp/abc.txt
請輸入內容,在單獨的一行輸入end表示結束。
(end to quit)> Hello World!
(end to quit)> chi le ma?
(end to quit)> the end
(end to quit)> end
[root@localhost day04]# ls /tmp/abc.txt
/tmp/abc.txt
[root@localhost day04]# cat /tmp/abc.txt
Hello World!
chi le ma?
the end
  1. 分析程序有哪些功能,將這些功能編寫成功能函數,形成程序的大體框架。
def get_fname():
    '用於獲取文件名,返回一個不存在文件名'

def get_content():
    '用於獲取內容,返回一個列表'

def wfile(fname, content):
    '需要文件名和內容作爲參數,將內容寫入文件'
  1. 編寫代碼的主體,按一定的規則調用相關函數
def get_fname():
    '用於獲取文件名,返回一個不存在文件名'

def get_content():
    '用於獲取內容,返回一個列表'

def wfile(fname, content):
    '需要文件名和內容作爲參數,將內容寫入文件'

if __name__ == '__main__':
    fname = get_fname()
    content = get_content()
    wfile(fname, content)
  1. 編寫每個具體的函數代碼
import os

def get_fname():
    '用於獲取文件名,返回一個不存在文件名'
    while 1:
        fname = input('文件名: ')
        # os.path.exists(fname),如果文件已存在返回True,不存在返回False
        if not os.path.exists(fname):
            break
        print('文件已存在,請重試。')

    return fname
def get_content():
    '用於獲取內容,返回一個列表'
    content = []  # 創建一個列表,用於存儲用戶輸入內容

    print('請輸入內容,在單獨的一行輸入end表示結束。')
    while 1:
        line = input('(end to quit)> ')
        if line == 'end':
            break

        # content.append(line + '\n')
        content.append(line)

    return content

def wfile(fname, content):
    '需要文件名和內容作爲參數,將內容寫入文件'
    with open(fname, 'w') as fobj:
        fobj.writelines(content)

if __name__ == '__main__':
    fname = get_fname()
    content = get_content()
    content = ['%s\n' % line for line in content]  # 給字串加上\n後,替換content變量
    wfile(fname, content)

序列對象相關的函數

在這裏插入圖片描述
在這裏插入圖片描述

  • reversed():翻轉序列對象,返回一個新的翻轉結果,不會改變原始對象
>>> reversed(seq)
<reversed object at 0x7f3f2ecf1be0>
>>> for zifu in reversed(seq):
...     print(zifu)
>>> list(reversed(seq))
['n', 'o', 'h', 't', 'y', 'p']
>>> l = [10, 20, 25, 30]
>>> list(reversed(l))
[30, 25, 20, 10]
>>> l
[10, 20, 25, 30]
  • sorted():排序,返回排序後的列表,不會改變對象本身
>>> sorted(seq)  # 按字符的大小排序
['h', 'n', 'o', 'p', 't', 'y']
>>> ord('a')   # a的ascii碼
97
>>> ord('A')
65
>>> ord('b')
98
>>> l
[10, 20, 25, 30]
>>> sorted(l)
[10, 20, 25, 30]
>>> l
[10, 20, 25, 30]
  • enumerate():可以同時得到下標和值
>>> list(enumerate(seq))
[(0, 'p'), (1, 'y'), (2, 't'), (3, 'h'), (4, 'o'), (5, 'n')]
>>> for data in enumerate(seq):  # data是元組
...     print(data)
...
(0, 'p')
(1, 'y')
(2, 't')
(3, 'h')
(4, 'o')
(5, 'n')
>>> for i, zifu in enumerate(seq):   # 可以將元組中的兩項分別賦值
...   print(i, zifu)
...
0 p
1 y
2 t
3 h
4 o
5 n

字符串

在這裏插入圖片描述
在這裏插入圖片描述
格式化操作符

# 基本形式:
>>> '' % ()
# 如果''中的佔位符只有一項,()可以省略不寫
>>> 'Hello %s' % 'tom'
'Hello tom'
# %s是將相應的數據轉換成str替代它
>>> '%s is %s years old' % ('tom', 20)
'tom is 20 years old'
# %d是整數
>>> '%s is %d years old' % ('tom', 20)
'tom is 20 years old'
>>> '%d is %d years old' % ('tom', 20)   # 報錯,因爲'tom'不能轉成整數
>>> '%s is %d years old' % ('tom', 20.5)  # 20.5保留整數
'tom is 20 years old'
>>> '%f' % (5 / 3)      # %f是浮點數
'1.666667'
>>> '%.2f' % (5 / 3)    # 保留兩位小數
'1.67'
>>> '%6.2f' % (5 / 3)   # 總寬度爲6,小數位2位,寬度不足6,左側補空格
'  1.67'

>>> '%10s%5s' % ('name', 'age')   # 第一個字段點10個寬度,第2個佔8個寬度,右對齊
'      name  age'
>>> '%10s%5s' % ('tom', 20)
'       tom   20'
>>> '%-10s%-5s' % ('name', 'age')  # 寬度爲負,表示左對齊
'name      age  '
>>> '%-10s%-5s' % ('tom', 20)
'tom       20   '
>>> '%#o' % 10   # 轉8進制
'0o12'
>>> '%#x' % 10   # 轉16進制
'0xa'
>>> '%e' % 12000  # 科學計數法,1.2乘以10的4次方
'1.200000e+04'

# 字符串格式化,還可以使用format方法,作爲了解
>>> '{} is {} years old'.format('tom', 20)
'tom is 20 years old'
>>> '{} is {} years old'.format(20, 'tom')
'20 is tom years old'
>>> '{1} is {0} years old'.format(20, 'tom')
'tom is 20 years old'

在這裏插入圖片描述

原始字符串

也叫真實字符串

>>> win_path = 'c:\temp\new.txt'
>>> print(win_path)   # 打印時\t是tab,\n是回車
c:      emp
ew.txt
>>> wpath = r'c:\temp\new.txt'  # 在字符串前加上r,表示字符串中的字符都是其字面>意義
>>> print(wpath)
c:\temp\new.txt
>>> wpath              # 直接寫變量名,將顯示python內部存儲時的樣式
'c:\\temp\\new.txt'
>>> win_path = 'c:\\temp\\new.txt'
>>> print(win_path)
c:\temp\new.txt

字符串方法

# strip用於去除字符串兩端的空白字符
>>> s1 = ' \thello world\n'
>>> s1.strip()
'hello world'
>>> s1.lstrip()  # 去除字符串左端的空白字符
'hello world\n'
>>> s1.rstrip()  # 去除字符串右端的空白字符
' \thello world'
>>> s2 = 'hello world'
>>> s2.upper()  # 轉大寫
'HELLO WORLD'
>>> s3 = 'HELLO'
>>> s3.lower()  # 轉小寫
'hello'
>>> s2.center(50)  # 總寬度50,居中
'                   hello world                    '
>>> s2.center(50, '*')  # 總寬度50,居中,使用*號填充兩側
'*******************hello world********************'
>>> s2.ljust(50, '#')   # 左對齊
'hello world#######################################'
>>> s2.rjust(50, '#')   # 右對齊
'#######################################hello world'
  • 創建adduser.py文件,實現以下目標:
    編寫一個程序,實現創建用戶的功能
    提示用戶輸入用戶名
    創建用戶並設置密碼
    將用戶相關信息寫入指定文件
import subprocess
import getpass
def adduser(user,passwd,fname):
    # 判斷用戶是否存在,存在則返回
    result = subprocess.run('id %s &> /dev/null' % user, shell=True)
    if result.returncode == 0:
        print('用戶已存在')
        return  # 函數的return類似於循環的break,它將結束函數,默認返回None

    # 創建用戶
    subprocess.run('useradd %s' % user, shell=True)
    # 設置密碼
    subprocess.run(
        'echo %s | passwd --stdin %s' % (passwd, user), shell=True)
    # 信息寫入文件
    info = '''用戶信息:
用戶: %s
密碼: %s
''' % (user, passwd)
    with open(fname,'a') as fobj:
        fobj.write(info)
        
if __name__ == '__main__':
    user=input('name: ')
    passwd=getpass.getpass()
    fname=input('filename: ')
    adduser(user,passwd,fname)
  • 創建fmtoutput.py腳本,要求如下:
    提示用戶輸入(多行)數據
    假定屏幕的寬度爲50,用戶輸入的多行數據如圖-1所示(文本內容居中):
    在這裏插入圖片描述
#!/usr/bin/env python3
def get_contents():
    contents = []
    print('請輸入內容,結束請輸入end。')
    while True:
        line = input('quit to end>')
        if line == 'end':
            break
        contents.append(line)
    return contents
width = 48
contents = get_contents()
print('+%s+' % ('*' * 48))
for line in contents:
    print('+{:^48}+'.format(line))    
print('+%s+' % ('*' * 48))
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章