用python寫乙個專業的傳參指令碼

2021-09-03 09:30:27 字數 2967 閱讀 4434

問:linux系統命令如ls,它有幾十個引數,可帶乙個或多個引數,可不分先後,用起來是非常的專業。但是自己寫的傳參指令碼,一般只傳乙個引數,如果傳多個,也是固定的順序,那麼如何用python寫出更專業的傳參指令碼呢?

答:使用python自帶的getopt模組。

1、語法:

import getopt

getopt.getopt(args,shortopts, longopts=)

#函式示例:getopt.getopt(sys.argv[1:],'u:p:p:h',["username=","password=","port=","help"])

#輸出格式:[('-p', '123'),('-u', 'root')]     #後面中括號包含沒有"-"或"--"的引數

2、引數說明:

args

所有傳參引數,一般用sys.argv[1:]表示,即所有傳參內容;

shortopts

短格式,一般引數如-u,-p,-h等(乙個"-"的)就是短格式;那寫在函式中就是"u:p:p:h",有冒號代表有引數,沒冒號代表沒引數。

longopts

長格式,一般引數如--username,--password,--help等(兩個"-"的)就是長格式;那寫在函式中就是["usrname=",'password=","help"],其中--help是沒有值的,所以沒有等於號。其它有等於號,表示後面需要引數。

3、演示效果:

短格式傳參:

[root@yang scripts]# python   getopt_test.py -u yangyun -p 123456 -p 2222

username: yangyun

password: 123456

port: 2222

長格式傳參:(也可以加=號)

[root@yang scripts]# python   getopt_test.py  --username yangyun   --password 123456 --port 2222

username: yangyun

password: 123456

port: 2222

長短格式都用:

[root@yang scripts]# python   getopt_test.py  --username=yangyun -p 123456   --port 2222

username: yangyun

password: 123456

port: 2222

只傳單個引數,其它是預設值:

[root@yang scripts]# python   getopt_test.py  -p 123456

username: root

password: 123456

port: 22

#此處port與user都用的預設值,預設值在函式裡指定

4、python傳參指令碼例項:

# cat  getopt_test.py

#!/usr/bin/python

#by yangyun 2015-1-11

import getopt 

import sys

#匯入getopt,sys模組

#定義幫助函式

def help():

print "usage error!"

sys.exit()

#輸出使用者名稱

def username(username):

print 'username:',username

#輸出密碼

def password(password):

if not password:

help()

else:

print 'password:',password

#輸出埠

def port(port):

print 'port:',port

#獲取傳參內容,短格式為-u,-p,-p,-h,其中-h不需要傳值。

#長格式為--username,--password,--port,--help,長格式--help不需要傳值。

opts,args=getopt.getopt(sys.argv[1:],'u:p:p:h',["username=","password=","port=","help"])

#print opts,'   ' ,args

#設定預設值變數,當沒有傳參時就會使用預設值。

username_value="root"

port_value='22'

password_value=''    #密碼不使用預設值,所以定義空。

#迴圈引數列表,輸出格式為:[('-p','123'), ('-u', 'root')]     

for opt,value in opts:

if opt in("-u","--username"):

username_value=value

#如果有傳參,則重新賦值。

if opt in("-p","--password"):

password_value=value

if opt in("-p","--port"):

port_value=value

if opt in("-h","--help"):

help()

#執行輸出使用者名稱、密碼、埠的函式,如果有變數沒有傳值,則使用預設值。

username(username_value)

password(password_value)

port(port_value)

用python寫乙個restful API

coding utf 8 package.module python實現的圖書的乙個restful api.restful api 一般模式 get select 從伺服器取出資源 一項或多項 post create 在伺服器新建乙個資源。put update 在伺服器更新資源 客戶端提供改變後的完...

python寫乙個服務 Python寫乙個服務

coding utf 8 import json from urllib.parse import parse qs from wsgiref.server import make server 定義函式,引數是函式的兩個引數,都是python本身定義的,預設就行了。定義檔案請求的型別和當前請求成功...

用python寫乙個蛇形矩陣

蛇形矩陣,如 10 11 12 1 9 16 13 2 8 15 14 3 7 6 5 4從右上角大回環,其實挺簡單,思路想明白了就順了。這樣的矩陣可以看做二維陣列,python對陣列的寫法很麻煩,用numpy生成就簡單多了 myarray np.zeros n,n dtype np.int16 有...