1. 配置文件(ConfigParser模块)

1.1 ConfigParser简介

ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value的options内容。例如

  1. [db]
  2. db_host = 127.0.0.1
  3. db_port = 22
  4. db_user = root
  5. db_pass = rootroot
  6.  
  7. [concurrent]
  8. thread = 10
  9. processor = 20

1.2 ConfigParser 初始工作

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

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

1.3 ConfigParser函数

1.3.1. 获取所有sections

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

1.3.2 获得指定section的options

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

1.3.3 获得指定sections的配置信息

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

1.3.4 获得指定sections的option的信息

  1. >>> cf.get("db", "db_host")
  2. '127.0.0.1'
  3. >>> cf.getint("db", "db_port")
  4. 22

同样有getfloat、getboolean

以下注意:凡是改变文件内容的,都要最后写入。

1.3.5 设置某个option的值

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

写入后的文件内容为

  1. [db]
  2. db_host = 127.1.1.1
  3. db_port = 22
  4. db_user = root
  5. db_pass = rootroot
  6.  
  7. [concurrent]
  8. thread = 10
  9. processor = 20

1.3.6 添加一个section

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

写入后的文件内容为

  1. [db]
  2. db_host = 127.1.1.1
  3. db_port = 22
  4. db_user = root
  5. db_pass = rootroot
  6.  
  7. [concurrent]
  8. thread = 10
  9. processor = 20
  10.  
  11. [jihite]
  12. int = 15
  13. bool = True
  14. float = 3.14

1.3.7 移除一个section

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

改变后的文件为

  1. [db]
  2. db_host = 127.1.1.1
  3. db_port = 22
  4. db_user = root
  5. db_pass = rootroot
  6.  
  7. [concurrent]
  8. thread = 10
  9. processor = 20
  10.  
  11. [jihite]
  12. bool = True
  13. float = 3.14

1.3.8 移除一个option

  1. >>> cf.remove_section("jihite")
  2. True
  3. >>> cf.write(open("config.ini", 'w'))

改变后的文件为

  1. [db]
  2. db_host = 127.1.1.1
  3. db_port = 22
  4. db_user = root
  5. db_pass = rootroot
  6.  
  7. [concurrent]
  8. thread = 10
  9. processor = 20  

1.4 ConfigParser举例

方式二:解析参数(argparse模块)

2. 解析参数(argparse模块)

2.1 argparse简介

argparse是python的命令行解析工具,它是Python标准库中推荐使用的编写命令行程序的工具。

2.2 argparser 初始工作

  1. import argparse
  2. parser = argparse.ArgumentParser()

类ArgumentParser定义为:

  1. 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] 

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

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

例子

del.py

  1. import argparse
  2. if __name__=="__main__":
  3. parser = argparse.ArgumentParser()
  4. parser.add_argument('content', help='content')
  5. parser.add_argument('title', help='title')
  6. parser.add_argument('tolist', help='tolist')
  7. args = parser.parse_args()
  8. content, title, tolist = args.content, args.title, args.tolist
  9.  
  10. mail=SMTP_SSL()
  11. mail.sendMail(content, title, tolist)

执行

  1. python2.7 del.py
  2. usage: del.py [-h] content title tolist
  3. del.py: error: too few arguments  

2.2.3

更多参数

  1. parser.add_argument("-v", "--verbose", help="increase output verbosity", action="store_true")
  2. parser.add_argument('numbers', type=int, help="numbers to calculate", nargs='+')
  3. parser.add_argument('-s', '--sum', help="sum all numbers", action='store_true', default=True)
  4. parser.add_argument('-f', '--format', choices=['int', 'float'], help='choose result format', default='idsf')

更详细参考

2.3 添加参数选项

http://www.cnblogs.com/linxiyue/p/3908623.html?utm_source=tuicool

3. 综合实例

要求

1. 配置文件和输入参数两种方式,其中输入参数优先级高

2. 参数包括配置文件、下载目录、进程个数、日志文件、日志类型

3. 如果进程个数不知,那么默认为机器cpu核数

4. 如果参数类型不知,那么默认为3

  1. def setArgs():
  2. parse = argparse.ArgumentParser(prog = "down_v9.py", usage="%(prog)s [options]")
  3. parse.add_argument("-c", "-config", type=str, help="配置文件")
  4. parse.add_argument("-o", "-outdir", type=str, help="下载目录")
  5. parse.add_argument("-p", "-processnum", type=int, help="进程个数")
  6. parse.add_argument("-l", "-logfile", type=str, help="日志文件")
  7. parse.add_argument("-lt", "-logtype", type=str, help="输出日志类型:1,只显示到屏幕;2,只输出到日志文件;3,即显示到屏幕又输出到日志文件")
  8. args = parse.parse_args()
  9. return args
  10.  
  11. def get_args():
  12. args = setArgs()
  13. config = args.c
  14. outdir = args.o
  15. process_num = args.p
  16. logfile = args.l
  17. logtype = args.lt
  18.  
  19. if config and os.path.isfile(config):
  20. cf = ConfigParser.ConfigParser()
  21. cf.read(config)
  22. s = cf.sections()
  23. if "con" in s:
  24. cons = cf.options("con")
  25. if outdir == None and "outdir" in cons:
  26. outdir = cf.get("con", "outdir")
  27. if process_num == None and "process_num" in cons:
  28. process_num = cf.getint("con", "process_num")
  29. if logfile == None and "logfile" in cons:
  30. logfile = cf.get("con", "logfile")
  31. if logtype == None and "logtype" in cons:
  32. logtype = cf.get("con", "logtype")
  33. if process_num == None:
  34. process_num = multiprocessing.cpu_count()
  35. if logtype == None:
  36. logtype = 3
  37.  
  38. return [outdir, process_num, logfile, logtype]

Python 参数设置的更多相关文章

  1. python matplotlib 中文显示参数设置

    python matplotlib 中文显示参数设置 方法一:每次编写代码时进行参数设置 #coding:utf-8import matplotlib.pyplot as pltplt.rcParam ...

  2. Python网络爬虫(1)--url访问及参数设置

    环境:Python2.7.9 / Sublime Text 2 / Chrome 1.url访问,直接调用urllib库函数即可 import urllib2 url='http://www.baid ...

  3. 使用python crontab设置linux定时任务

    熟悉linux的朋友应该知道在linux中可以使用crontab设置定时任务.可以通过命令crontab -e编写任务.当然也可以直接写配置文件设置任务. 但是有时候希望通过脚本自动设置,比如我们应用 ...

  4. LIBSVM使用方法及参数设置 主要参考了一些博客以及自己使用经验。

    主要参考了一些博客以及自己使用经验.收集来觉得比较有用的. LIBSVM 数据格式需要---------------------- 决策属性  条件属性a  条件属性b  ... 2    1:7   ...

  5. 详解使用python crontab设置linux定时任务

    熟悉linux的朋友应该知道在linux中可以使用crontab设置定时任务.可以通过命令crontab -e编写任务.当然也可以直接写配置文件设置任务. 但是有时候希望通过脚本自动设置,比如我们应用 ...

  6. LIBSVM使用方法及参数设置

    LIBSVM 数据格式需要---------------------- 决策属性 条件属性a 条件属性b ... 2 1:7 2:5 ... 1 1:4 2:2 ... 数据格式转换--------- ...

  7. Python参数类型以及实现isOdd函数,isNum函数,multi函数,isPrime函数

    Python参数类型以及实现isOdd函数,isNum函数,multi函数,isPrime函数 一.Python参数类型 形参:定义函数时的参数变量. 实参:调用函数时使用的参数变量. 参数传递的过程 ...

  8. python 参数定义库argparse

    python 参数定义库argparse 这一块的官方文档在这里 注意到这个库是因为argparse在IDE中和在ipython notebook中使用是有差异的,习惯了再IDE里面用,转到ipyth ...

  9. QGridLayout栅格布局函数参数设置

    对于PyQt5的栅格布局函数,主要是实现多个控件之间的栅格布局形式,一般有两种设置方式: 1.Qdesigner布局设置时直接使用栅格布局函数,便可以把所需要布局的控件直接按照栅格方式来进行布局: 2 ...

随机推荐

  1. 查询sql语句的执行时间

    我们开启执行计划来看sql语句的执行效率,看下索引是否使用等 但是执行计划没有告诉我们执行时间,刚刚看了一个代码,可以自己计算执行时间的 Declare @d Datetime      Set @d ...

  2. CentOS6.5上Zabbix3.0的RPM安装【四】-乱码

    当Agent添加完成后,部分显示(如cpu负载)出现乱码情况: 解决步骤如下: 1, 在windows7中找一个自己喜欢的字体或者去网上下载一个字体.[以“楷体 常规”为例] 2, 右击”楷体 常规” ...

  3. vue 用axios实现调用接口下载excel

    了解的方式有两种: 1. 用a标签,href设置为后端提供的excel接口 <a href="excel接口">导出</a> 简单方便,缺点就是当有toke ...

  4. asp web.config文件里compilation的assemblies add的元素来自哪里

    该程序集组合由版本.区域性和公钥标记组成. ASP.NET 首先在应用程序的专用 Bin 目录中搜索程序集 DLL,然后在系统程序集缓存中搜索程序集 DLL. add 元素添加要在动态资源编译期间使用 ...

  5. JBOSS在win7环境下启动run.bat无反应

    今天从隔壁机器拷贝了一份Jboss,却发现启动无任何反应. 仔细对比了jdk jboss的各项参数发现都是相同,无奈之下,检查run.bat文件 发现时在此句出现前后 无反应: "%JAVA ...

  6. 前端开发快速定位bug的一些小技巧

    1,根据报错信息定位: (1) Uncaught TypeError: Cannot read property 'attr' of undefined; 此类型为变量或者对象属性未定义类型. (2) ...

  7. P1114 “非常男女”计划

    题意:给你一个01串,求满足0和1总数相等的最大字串   $n\ \le\ 10^5$ 1.$O(n^3)$枚举起点终点,统计判断是否成立 2.$O(n^2)$先$O(n)$时间计算01个数的前缀和, ...

  8. luogu4430 小猴打架

    假硕讲了个prufer编码和Caylay公式 我为了证明prufer编码没用 所以用矩阵树定理证明了Caylay公式 让我们用矩阵树定理推一波 首先这个小猴打架最后会打成一棵树,这棵树是N个点的完全图 ...

  9. ios对new Date() 的兼容问题

    移动开发的一个小坑 我们一般这样创建一个日期变量 var d = new Date("2017-08-11 12:00:00"); 但是在ios上却是返回 invalid Date ...

  10. CF352A Jeff and Digits

    Jeff's got n cards, each card contains either digit 0, or digit 5. Jeff can choose several cards and ...