34fw 发表于 2015-1-14 09:04:09

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

问:linux系统命令如ls,它有几十个参数,可带一个或多个参数,可不分先后,用起来是非常的专业。但是自己写的传参脚本,一般只传一个参数,如果传多个,也是固定的顺序,那么如何用python写出更专业的传参脚本呢?答:使用python自带的getopt模块。
1、语法:
import getoptgetopt.getopt(args,shortopts, longopts=[])#函数示例:getopt.getopt(sys.argv,'u:p:P:h',["username=","password=","port=","help"])#输出格式:[('-p', '123'),('-u', 'root')][]   #后面中括号包含没有"-"或"--"的参数
2、参数说明:
args      所有传参参数,一般用sys.argv表示,即所有传参内容;shortopts短格式,一般参数如-u,-p,-h等(一个"-"的)就是短格式;那写在函数中就是"u:p:P:h",有冒号代表有参数,没冒号代表没参数。longopts长格式,一般参数如--username,--password,--help等(两个"-"的)就是长格式;那写在函数中就是["usrname=",'password=","help"],其中--help是没有值的,所以没有等于号。其它有等于号,表示后面需要参数。
3、演示效果:
短格式传参:
# python   getopt_test.py -u yangyun -p 123456 -P 2222username: yangyunpassword: 123456port: 2222
长格式传参:(也可以加=号)
# python   getopt_test.py--username yangyun   --password 123456 --port 2222username: yangyunpassword: 123456port: 2222
长短格式都用:
# python   getopt_test.py--username=yangyun -p 123456   --port 2222 username: yangyunpassword: 123456port: 2222
只传单个参数,其它是默认值:
# python   getopt_test.py-p 123456 username: rootpassword: 123456port: 22#此处port与user都用的默认值,默认值在函数里指定
4、python传参脚本实例:
# catgetopt_test.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/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,'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)







页: [1]
查看完整版本: 用python写一个专业的传参脚本