1、使用sys.argv獲取命令行參數
sys.argv就是一個保存命令行參數的普通列表
示例:
#!/usr/bin/python3 # -*-coding:UTF-8-*-
import os import sys def main(): sys.argv.append("") filename = sys.argv[1] # 如果用戶直接運行程序,沒有傳遞任何命令行參數,那么訪問sys.argv[1]將會出現索引越界的錯誤,為了避免這個錯誤,在訪問sys.argv之前先向sys.argv中添加一個空的字符串
if not os.path.isfile(filename): # 判斷文件是否存在
raise SystemExit(filename + ' does not exists') elif not os.access(filename, os.R_OK): # 如果文件存在,則使用os.access函數判斷是否具有對文件的讀權限
raise SystemExit(filename + ' is not accessible') else: print(filename + ' is accessible') if __name__ == '__main__': main()
2、使用sys.stdin和fileinput讀取標准輸入
(1)sys.stdin
示例:
#!/usr/bin/python3 # -*-coding:UTF-8-*-
import sys for line in sys.stdin: print(line, end="") 或者 def get_content(): return sys.stdin.readlines() print(get_content())
執行:
python3 xxx.py < /etc/passwd
cat /etc/passwd | python3 xxx.py
(2)fileinput
fileinput讀取內容比sys.stdin更加靈活,fileinput既可以從標准輸入中讀取數據,也可以從文件中讀取數據
示例:
#!/usr/bin/python3 # -*-coding:UTF-8-*-
import fileinput for line in fileinput.input(): print(line, end="")
執行:
python3 xxx.py < /etc/passwd
cat /etc/passwd | python3 xxx.py
python3 xxx.py /etc/passwd /etc/hosts
因為fileinput可以讀多個文件內容,所以,fileinput提供了一些方法可以知道當前所讀的內容屬於哪一個文件。fileinput中常用的方法有:
filename:當前正在讀取的文件名
fileno:文件的描述符
filelineno:正在讀取的行是當前文件的第幾行
isfirstline:正在讀取的行是否當前文件的第一行
isstdin:正在讀取文件還是直接從標准輸入讀取內容
示例:
#!/usr/bin/python3 # -*-coding:UTF-8-*-
import fileinput for line in fileinput.input(): meta = [fileinput.filename(), fileinput.fileno(), fileinput.filelineno(), fileinput.isfirstline(), fileinput.isstdin()] print(*meta, end="") print(line, end="")
3、使用SystemExit異常打印錯誤信
文件描述符 | 用途 | POSIX名稱 | stdio流 |
0 | 標准輸入 | STDIN_FILENO | stdin |
1 | 標准輸出 | STDOUT_FILENO | stdout |
2 | 標准錯誤 | STDERR_FILENO | stderr |
示例:
#!/usr/bin/python3 # -*-coding:UTF-8-*-
import sys sys.stdout.write('hello') sys.stderr.write('world') sys.stderr.write('error message') sys.exit(1) # raise SystemExit("error message")
執行:
python3 xxx.py >/dev/null
結果:worlderror message
python3 xxx.py 2>/dev/null
結果:hello
4、使用getpass庫讀取密碼
getuser函數用來從環境變量中獲取用戶名,后者用來等待用戶輸入密碼。getpass函數和input函數的區別在於,它不會將輸入的密碼顯示在命令行中,從而避免輸入的密碼被他人看到
示例:
#!/usr/bin/python3 # -*-coding:UTF-8-*-
import getpass user = getpass.getuser() passwd = getpass.getpass("your password: ") print(user,passwd)
5、使用ConfigParse解析配置文件
注意:在Python3中,ConfigParser模塊重命名為configparser模塊,使用上有細微差異
一個典型的配置文件包含一到多個章節(section),每個章節下可以包含一個到多個選項(option)
下面以MySQL的配置文件為例:
[mysqld] basedir = /usr datadir = /var/lib/mysql tmpdir = /tmp skip-external-locking [client] user = mysql password = mysql port = 3306 host = 127.0.0.1
configparser中有很多的方法,其中與讀取配置文件,判斷配置項相關的方法有:
sections:返回一個包含所有章節的列表
has_section:判斷章節是否存在
items:以元組的形式返回所有選項
options:返回一個包含章節下所有選項的列表
has_option:判斷某個選項是否存在
get、getboolean、getint、getfloat:獲取選項的值
示例:
#!/usr/bin/python3 # -*-coding:UTF-8-*-
import configparser temp = configparser.ConfigParser(allow_no_value=True) # allow_no_value=False,表示配置文件中是否允許選項沒有值的情況
temp.read('my.cnf') print(temp.sections()) print(temp.has_section('client')) print(temp.options('client')) print(temp.has_option('client', 'user')) print(temp.get('client', 'host')) print(temp.getint('client', 'port'))
配置文件中有2個章節,分別是mysqld和client。其中,client章節有4個選項。可以通過sections方法獲取所有的章節,通過options方法獲取某個章節下所有的選項,也可以通過has_section方法判斷某個章節是否存在,通過has_option方法判斷某個選項是否存在。
在讀取選項的內容時,get方法默認以字符串的形式返回。如果需要讀取一個整數,則使用getint方法讀取;如果需要讀取一個布爾的取值,則使用getboolean方法讀取。
configparser也提供了許多方法便於修改配置文件:
remove_section:刪除一個章節
add_section:添加一個章節
remove_option:刪除一個選項
set:添加一個選項
write:將configparser對象中的數據保存到文件中
示例:
#!/usr/bin/python3 # -*-coding:UTF-8-*-
import configparser temp = configparser.ConfigParser(allow_no_value=True) temp.read('my.cnf') temp.remove_section('client') temp.add_section('mysql') temp.set('mysql', 'host', '127.0.0.1') temp.set('mysql', 'port', '3306') temp.write(open('my.cnf', 'w'))