Python命令行参数详解与PEP 8规范实践指南
一、命令行参数
在使用Python开发脚本,作为一个运维工具,或者其他工具需要接受用户参数运行时,这里就可以用到命令行传参的方式,可以给使用者提供一个比较友好的交互体验。
在Python中,最常用的命令行参数解析方式是使用sys.argv和argparse
1、sys.argv
创建一个test.py文件
import sys
print('参数个数为:',len(sys.argv),'个参数')
print('参数列表:',str(sys.argv))
$ python test.py hello 1 2
参数个数为: 4 个参数
参数列表: ['test.py', 'hello', '1', '2']
str(sys.argv) 是命令行参数列表
len(sys.argv) 是命令行参数个数
sys.argv[0] 表示脚本名
2、getopt模块
getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式 – 和长选项模式 –。
该模块提供了两个方法及一个异常处理来解析命令行参数。
getopt.getopt 方法
getopt.getopt 方法用于解析命令行参数列表,语法格式如下:
getopt.getopt(args, options[, long_options])
方法参数说明:
args: 要解析的命令行参数列表。
options : 以字符串的格式定义,options 后的冒号 : 表示如果设置该选项,必须有附加的参数,否则就不附加参数。
long_options : 以列表的格式定义,long_options 后的等号 = 表示该选项必须有附加的参数,不带等号表示该选项不附加参数。
该方法返回值由两个元素组成: 第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有 – 或 — 的参数。
Exception getopt.GetoptError
在没有找到参数列表,或选项的需要的参数为空时会触发该异常。
异常的参数是一个字符串,表示错误的原因。属性 msg 和 opt 为相关选项的错误信息。
实例
假定我们创建这样一个脚本,可以通过命令行向脚本文件传递两个文件名,同时我们通过另外一个选项查看脚本的使用。脚本使用方法如下:
usage: test.py -i <inputfile> -o <outputfile>
test.py 文件代码如下所示:
实例
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print 'test.py -i <inputfile> -o <outputfile>'
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print '输入的文件为:', inputfile
print '输出的文件为:', outputfile
if __name__ == "__main__":
main(sys.argv[1:])
执行以上代码,输出结果为:
$ python test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ python test.py -i inputfile -o outputfile
输入的文件为: inputfile
输出的文件为: outputfile
3、argparse
argparse 模块可以轻松编写用户友好的命令行界面。该程序定义了它需要的参数,argparse 并将找出如何解析这些参数sys.argv。该argparse 模块还会自动生成帮助和用法消息,并在用户给出程序无效参数时发出错误
import argparse
from argparse import _AttributeHolder, _ActionsContainer
parse = argparse.ArgumentParser()
# ArgumentParser 类的初始化方法
class ArgumentParser(_AttributeHolder, _ActionsContainer):
"""Object for parsing command line strings into Python objects.
Keyword Arguments:
- prog -- The name of the program (default: sys.argv[0])
- usage -- A usage message (default: auto-generated from arguments)
- description -- A description of what the program does
- epilog -- Text following the argument descriptions
- parents -- Parsers whose arguments should be copied into this one
- formatter_class -- HelpFormatter class for printing help messages
- prefix_chars -- Characters that prefix optional arguments
- fromfile_prefix_chars -- Characters that prefix files containing
additional arguments
- argument_default -- The default value for all arguments
- conflict_handler -- String indicating how to handle conflicts
- add_help -- Add a -h/-help option
- allow_abbrev -- Allow long options to be abbreviated unambiguously
"""
def __init__(self,
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,
allow_abbrev=True):
pass
参数说明:
prog :文件名,默认为sys.argv[0],用来在help信息中描述程序的名称。
usage :描述程序用途的字符串
description :help信息前显示的信息
epilog :help信息之后显示的信息
import argparse
parser = argparse.ArgumentParser(prog='my - program', usage='%(prog)s
[options] usage',description = 'my - description',epilog = 'my - epilog')
print(parser.print_help())
执行输出:
python@python:~$ python3 test.py usage: my - program [options] usage my - description optional arguments: -h, --help show this help message and exit my - epilog None
parents :由ArgumentParser对象组成的列表,它们的arguments选项会被包含到新ArgumentParser对象中。(类似于继承)
formatter_class :help信息输出的格式,为了美观…
prefix_chars :参数前缀,默认为’-‘(最好不要修改)
fromfileprefixchars :前缀字符,放在文件名之前
add_help :是否增加-h/-help选项 (默认为True),一般help信息都是必须的。设为False时,help信息里面不再显示-h –help信息
argument_default: – (default: None)设置一个全局的选项的缺省值,一般每个选项单独设置,基本没用
4、添加参数选项 – add_argument
ArgumentParser.add_argument(name or flags...[, action][, nargs][, const]
[, default][, type][, choices][, required]
[, help][, metavar][, dest]
)
name or flags :参数有两种,可选参数和位置参数。 添加可选参数 parser.add_argument('-f', '–foo') 添加位置参数 parser.add_argument('bar') parse_args()运行时,默认会用’-‘来认证可选参数,剩下的即为位置参数, 位置参数必须传
action参数 默认为store
1、store_const:值存放在const中:
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--foo', action='store_const', const=12)
>>> parser.parse_args('--foo'.split()) Namespace(foo=12)
2、append:存为列表,可以有多个参数
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('-l', action='append')
args = parser.parse_args()
print(args)
执行结果:
python@python:~$ python3 test.py -l 1 -l 3 Namespace(l=['1', '3'])
3、help: help信息
4、version:版本
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--version', action='version', version='version 2.0')
rest = parser.parse_args()
metaver:帮助信息中显示的参数名称
const :保存一个常量
default :默认值
type :参数类型,默认为str
choices :设置参数值的范围,如果choices中的类型不是字符串,记得指定type
required :该选项是否必选,默认为True
dest :参数名
# 创建一个解析器对象
import argparse
parse=argparse.ArgumentParser(prog='my - 我自己的程序', usage='%(prog)s [options] usage',
description = 'my-编写自定义命令行的文件',epilog = 'my - epilog')
# 添加位置参数【必选参数】
parse.add_argument('name',type=str, help='你自己的名字')
parse.add_argument('age',type=str,help='你的年龄')
# 添加可选参数
# parse.add_argument('-s','--sex', action='append',type=str,help='你的性别')
# 限定一个范围
parse.add_argument('-s','--sex',default='男', choices=['男','femal','女','male'],type=str,help='你的性别')
# print(parse.print_help())
result=parse.parse_args() #开始解析参数
print(result.name,result.age,result.sex)
输出:
usage: my - 我自己的程序 [options] usage
my - 我自己的程序: error: the following arguments are required: name, age
登录:
import argparse
# 创建一个解析器对象
parse=argparse.ArgumentParser(prog='系统登录', usage='%(prog)s [options] usage',
description='系统自定义命令行的文件',epilog = 'my - epilog')
# 添加位置参数【必选参数】
parse.add_argument('loginType',type=str, help='登录系统类型')
# 添加可选参数
parse.add_argument('-u',dest='user',type=str,help='你的用户名')
parse.add_argument('-p',dest='pwd',type=str,help='你的密码')
result=parse.parse_args() #开始解析参数
if (result.user=='root' and result.pwd=='111111'):
print('login sucess!')
else:
print('login fail!')
二、PEP 8规范
PEP 8,即Python Enhancement Proposal #8,是Python社区为了统一代码风格而制定的一组编码规范。它包括了代码布局、命名规范、注释风格和具体语法等方面的建议。虽然PEP 8中的规范并非强制性规定,但遵循这些规范的代码被认为更具可读性和可维护性,因此,许多Python项目都要求其源代码符合PEP 8规范。
命名规范
Python工程项目命名规则主要包括以下几个方面:
1、项目工程名:项目工程名应使用首字母大写加驼峰命名法,例如ProjectName。
2、包名和模块名:包名和模块名应全部使用小写字母,并且使用下划线分隔。例如,mypackage、module_name。
3、文件名:文件名也应全部使用小写字母,并且使用下划线分隔。例如,module_name.py。
4、类名:类名应使用首字母大写的驼峰命名法(Pascal命名法)。例如,ClassName。私有类名称需要在类名前加一个下划线,例如_ClassName。
5、函数名:函数名应全部使用小写字母,并且使用下划线分隔。例如,function_name。私有函数名称需要在函数名前加一个下划线,例如_function_name。
6、全局变量、常量:全局变量和常量应全部使用大写字母,并且使用下划线分隔。例如,GLOBAL_VAR_NAME、CONSTANT_NAME。
7、方法名、函数参数、实例变量:这些命名也应全部使用小写字母,并且使用下划线分隔。例如,method_name、function_parameter_name、instance_var_name。
8、私有变量和方法:私有变量和方法名称需要在名称前加一个下划线。例如,_variable_name、_method_name
9、变量:(1)变量名只能包含字母(a – z,A – Z)、数字和下划线(_)(2)变量名不能以数字开头(3)区分大小写(4)不能使用Python的保留字作为变量名。
Python中关键字如下:
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
以下是一些变量名的命名方法:
【1】小写加下划线(常用于内部或私有变量):age_of_user
【2】大驼峰体(常用于类名):UserName, FirstName
【3】小驼峰体(常用于函数名和实例变量):ageOfUser, firstName
缩进
#与开头分隔符对齐
foo = long_function_name(var_one,var_two,
var_three,var_four)
#包含更多缩进以区别于此。
def long_function_name(
var_one,var_two,var_three,
var_four):
print(var_one)
#悬挂缩进应该添加一个关卡。
foo = long_function_name(
var_one,var_two,
var_three,var_four)
行宽
空行
导入
from module import *
,以防命名冲突。表达式和语句中的空格
=
)、比较(==
, <
, >
, !=
, <>
, <=
, >=
, in
, not in
, is
, is not
),以及字典的键值对之间使用空格。注释
命名约定
编码
其他
import
中同时导入多个库。self
。作者:MinggeQingchun