用python写一个专业的传参脚本

问: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都用的默认值,默认值在函数里指定

 

4python传参脚本实例:

# 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,传参,getopt)