標籤:false count image png shell指令碼 option return __name__ filename
1. 將命令列參數儲存在列表中,注意argv[0]是程式本身的名字:
import sysprint(sys.argv) print(sys.argv[1])
python argv.py localhost 3306
[‘argv.py‘, ‘localhost‘, ‘3306‘]
localhost
2. 使用sys.stdin和fileinput讀取標準輸入,並列印在終端類似shell中的管道
import sys for line in sys.stdin:print(line,end="")
可以像shell指令碼一樣,同過標準輸入給程式輸入內容
python read_stdin.py </etc/passwd
python read_stdin.py -
cat /etc/passwd |python read_stdin.py
將標準輸入儲存在一個列表中
import sysdef get_content(): return sys.stdin.readlines() print(get_content())
python readlines_stdin.py <test/1.txt
[‘hello\n‘, ‘world\n‘]
3. 利用fileinput讀取標準輸入
#/usr/bin/env python#coding=utf-8 import fileinputfor line in fileinput.input(): print(line,end="")
python file_input1.py /etc/passwd
python file_input1.py </etc/passwd
python file_input1.py /etc/passwd /etc/my.cnf
fileinput常用的方法:
#!/usr/bin/pythonfrom __future__ import print_functionimport fileinputfor line in fileinput.input(): meta = [fileinput.filename(), fileinput.fileno(), fileinput.filelineno(), fileinput.isfirstline(), fileinput.isstdin()] print(*meta, end="")
print() print(line, end="")
4. 使用getpass讀取密碼:
import getpassuser=getpass.getuser()passwd=getpass.getpass(‘you password: ‘) print(user,passwd)
可以避免輸入密碼被看見
5.使用argparse解析命令列參數
agrparse能夠根據從sys.arg中解析參數,並自動產生協助資訊
from __future__ import print_functionimport argparsedef _argparse(): parser = argparse.ArgumentParser(description="This is description") parser.add_argument(‘--host‘, action=‘store‘, dest=‘server‘,default="localhost", help=‘connect to host‘) parser.add_argument(‘-t‘, action=‘store_true‘, default=False, dest=‘boolean_switch‘, help=‘Set a switch to true‘) return parser.parse_args()def main(): parser = _argparse() print(parser) print(‘host =‘, parser.server) print(‘boolean_switch=‘, parser.boolean_switch)if __name__ == ‘__main__‘: main()
格式:rgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])
name:參數的名字
action: 遇到參數時的動作
nargs:參數的個數
dest:解析後的參數的名字
type:參數的類型
6. 使用Click建立命令列解析
Click比較argparse更加的快速和簡單
pip inst click
import click@click.command()@click.option(‘--count‘, default=1, help=‘Number of greetings.‘)@click.option(‘--name‘, prompt=‘Your name‘, help=‘The person to greet.‘)def hello(count, name): """Simple program that greets NAME for a total of COUNT times.""" for x in range(count): click.echo(‘Hello %s!‘ % name)if __name__ == ‘__main__‘: hello()
commond讓函數成為命令列介面
option:增加命令列選項
echo:輸出結果
prompt:如果沒有指定name這個參數時,會進入互動模式下輸入
也可以像Linux中的fc一樣進入預設編輯器
import clickmessage = click.edit()print(message,end="")
Python處理命令列參數