设为首页 收藏本站
查看: 1230|回复: 0

[经验分享] Python 参数设置

[复制链接]

尚未签到

发表于 2015-11-30 13:48:51 | 显示全部楼层 |阅读模式
1. 配置文件(ConfigParser模块)
  1.1 ConfigParser简介
  ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value的options内容。例如



[db]
db_host = 127.0.0.1
db_port = 22
db_user = root
db_pass = rootroot
[concurrent]
thread = 10
processor = 20

  
  1.2 ConfigParser 初始工作
  使用ConfigParser 首选需要初始化实例,并读取配置文件:



import ConfigParser
cf = ConfigParser.ConfigParser()
cf.read("配置文件名")

  
  1.3 ConfigParser函数
  1.3.1. 获取所有sections



>>> s = cf.sections()
>>> print s
['db', 'concurrent']

  1.3.2 获得指定section的options



>>> cf.options('db')
['db_host', 'db_port', 'db_user', 'db_pass']

  1.3.3 获得指定sections的配置信息



>>> cf.items('db')
[('db_host', '127.0.0.1'), ('db_port', '22'), ('db_user', 'root'), ('db_pass', 'rootroot')]

  1.3.4 获得指定sections的option的信息



>>> cf.get("db", "db_host")
'127.0.0.1'
>>> cf.getint("db", "db_port")
22

  同样有getfloat、getboolean
  以下注意:凡是改变文件内容的,都要最后写入。
  1.3.5 设置某个option的值



>>> cf.set("db", "db_host", "127.1.1.1")
>>> cf.write(open("config.ini", 'w'))

  写入后的文件内容为



[db]
db_host = 127.1.1.1
db_port = 22
db_user = root
db_pass = rootroot
[concurrent]
thread = 10
processor = 20

  1.3.6 添加一个section



>>> cf.add_section("jihite")
>>> cf.set("jihite", "int", "15")
>>> cf.set("jihite", "bool", "True")
>>> cf.set("jihite", "float", "3.14")
>>> cf.write(open("config.ini", 'w'))

  写入后的文件内容为



[db]
db_host = 127.1.1.1
db_port = 22
db_user = root
db_pass = rootroot
[concurrent]
thread = 10
processor = 20
[jihite]
int = 15
bool = True
float = 3.14

  1.3.7 移除一个section



>>> cf.remove_option("jihite", "int")
True
>>> cf.write(open("config.ini", 'w'))

  改变后的文件为



[db]
db_host = 127.1.1.1
db_port = 22
db_user = root
db_pass = rootroot
[concurrent]
thread = 10
processor = 20
[jihite]
bool = True
float = 3.14

  1.3.8 移除一个option



>>> cf.remove_section("jihite")
True
>>> cf.write(open("config.ini", 'w'))
  改变后的文件为



[db]
db_host = 127.1.1.1
db_port = 22
db_user = root
db_pass = rootroot
[concurrent]
thread = 10
processor = 20  
  1.4 ConfigParser举例
  
  方式二:解析参数(argparse模块)
  

2. 解析参数(argparse模块)
  2.1 argparse简介
  argparse是python的命令行解析工具,它是Python标准库中推荐使用的编写命令行程序的工具。
  
  2.2 argparser 初始工作



import argparse
parser = argparse.ArgumentParser()

  类ArgumentParser定义为:



class ArgumentParser(prog=None, usage=None, description=None, epilog=None, parents=[], formatter_class=argparse.HelpFormatter, prefix_chars='-', fromfile_prefix_chars=None, argument_default=None, conflict_handler='error', add_help=True)

  参数的含义为
  2.2.1 prog:程序的名字,默认为sys.argv[0] 



>>> parser = argparse.ArgumentParser(prog="myprogram")
>>> parser.print_help()
usage: myprogram [-h]
optional arguments:
-h, --help  show this help message and exit

  2.2.2 usage: 描述程序用途的字符串



>>> parser = argparse.ArgumentParser(prog="myprogram", usage="%(prog)s [options]")
>>> parser.print_help()
usage: myprogram [options]
optional arguments:
-h, --help  show this help message and exit

  2.2.3 description: help信息前的文字



>>> parser.print_help()
usage: myprogram [options]
Create my own program
optional arguments:
-h, --help  show this help message and exit

  2.2.4 epilog:help之后的文字



>>> parser = argparse.ArgumentParser(prog="myprogram", usage="%(prog)s [options]", description="Create my own program", epilog="And that's how you'd foo a bar")
>>> parser.print_help()
usage: myprogram [options]
Create my own program
optional arguments:
-h, --help  show this help message and exit
And that's how you'd foo a bar

  2.2.5   
  更详细参考
  
  2.3 添加参数选项
  http://www.cnblogs.com/linxiyue/p/3908623.html?utm_source=tuicool
  

3. 综合实例
  要求
  1. 配置文件和输入参数两种方式,其中输入参数优先级高
  2. 参数包括配置文件、下载目录、进程个数、日志文件、日志类型
  3. 如果进程个数不知,那么默认为机器cpu核数
  4. 如果参数类型不知,那么默认为3



def setArgs():
parse = argparse.ArgumentParser(prog = "down_v9.py", usage="%(prog)s [options]")
parse.add_argument("-c", "-config", type=str, help="配置文件")
parse.add_argument("-o", "-outdir", type=str, help="下载目录")
parse.add_argument("-p", "-processnum", type=int, help="进程个数")
parse.add_argument("-l", "-logfile", type=str, help="日志文件")
parse.add_argument("-lt", "-logtype", type=str, help="输出日志类型:1,只显示到屏幕;2,只输出到日志文件;3,即显示到屏幕又输出到日志文件")
args = parse.parse_args()
return args
def get_args():
args = setArgs()
config = args.c
outdir = args.o
process_num = args.p
logfile = args.l
logtype = args.lt
if config and os.path.isfile(config):
cf = ConfigParser.ConfigParser()
cf.read(config)
s = cf.sections()
if "con" in s:
cons = cf.options("con")
if outdir == None and "outdir" in cons:
outdir = cf.get("con", "outdir")
if process_num == None and "process_num" in cons:
process_num = cf.getint("con", "process_num")
if logfile == None and "logfile" in cons:
logfile = cf.get("con", "logfile")
if logtype == None and "logtype" in cons:
logtype = cf.get("con", "logtype")
if process_num == None:
process_num = multiprocessing.cpu_count()
if logtype == None:
logtype = 3
return [outdir, process_num, logfile, logtype]
  

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-145421-1-1.html 上篇帖子: python socketpool:通用连接池 下篇帖子: 【python游戏编程之旅】第二篇--pygame中的IO、数据
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表