命令行参数及全局替换程序

知识内容:

1.python命令行参数

2.全局替换程序

一、python命令行参数

1.什么是命令行参数

简单说在命令行中给定的参数就是命令行参数,命令行的参数以空格隔开

eg:  编译C语言生成一个exe文件后用命令行来输入一些参数

./res.exe this is some parameter中的this is some parameter是字符串参数

2.python中的命令行参数

(1)python中的命令行参数

在Python里,命令行的参数和C语言很类似(因为标准Python是用C语言实现的)。在C语言里,main函数的原型为int main(int argc, char **argv),这里主要指linux平台, argc指的是命令行传入的参数个数(程序的name为第一个参数),而argv则是一个指针数组,每一个元素为指向一个命令行参数的指针。在Python里的命令行参数是存储在sys.argv里,argv是一个列表,第一个元素为程序名称

使用方法:  python name.py arg1 arg2 arg3

取命令行参数:  sys模块和getopt模块

(2)sys模块取命令行参数

Python 中也可以所用 syssys.argv 来获取命令行参数:

  • sys.argv 是命令行参数列表。

  • len(sys.argv) 是命令行参数个数。

实例:

1 import sys
2 
3 print("参数个数为: %d" % len(sys.argv))
4 print("参数列表为: %s" % str(sys.argv))

将以上代码保存为test.py在命令行中运行,得到的结果如下:

1 D:wybpythonoldboy>python3 test.py 1 2 3 4 5
2 参数个数为: 6
3 参数列表为: ['test.py', '1', '2', '3', '4', '5']

(3)getopt模块取命令行参数

getopt模块是专门处理命令行参数的模块,用于获取命令行选项和参数,也就是sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式(-)和长选项模式(--),该模块提供了两个方法及一个异常处理来解析命令行参数

这里我主要介绍以下这种方法: getopt.getopt 方法

getopt.getopt 方法用于解析命令行参数列表,语法格式如下:

getopt.getopt(args, options[, long_options])

方法参数说明:

  • args: 要解析的命令行参数列表。

  • options: 以列表的格式定义,options后的冒号(:)表示该选项必须有附加的参数,不带冒号表示该选项不附加参数。

  • long_options: 以字符串的格式定义,long_options 后的等号(=)表示如果设置该选项,必须有附加的参数,否则就不附加参数。

  • 该方法返回值由两个元素组成: 第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有'-'或'--'的参数。

 官方解释:

 1 getopt(args, shortopts, longopts=[])
 2         getopt(args, options[, long_options]) -> opts, args
 3 
 4         Parses command line options and parameter list.  args is the
 5         argument list to be parsed, without the leading reference to the
 6         running program.  Typically, this means "sys.argv[1:]".  shortopts
 7         is the string of option letters that the script wants to
 8         recognize, with options that require an argument followed by a
 9         colon (i.e., the same format that Unix getopt() uses).  If
10         specified, longopts is a list of strings with the names of the
11         long options which should be supported.  The leading '--'
12         characters should not be included in the option name.  Options
13         which require an argument should be followed by an equal sign
14         ('=').
15 
16         The return value consists of two elements: the first is a list of
17         (option, value) pairs; the second is the list of program arguments
18         left after the option list was stripped (this is a trailing slice
19         of the first argument).  Each option-and-value pair returned has
20         the option as its first element, prefixed with a hyphen (e.g.,
21         '-x'), and the option argument as its second element, or an empty
22         string if the option has no argument.  The options occur in the
23         list in the same order in which they were found, thus allowing
24         multiple occurrences.  Long and short options may be mixed.

实例: 

 1 import getopt
 2 import sys
 3 
 4 
 5 def usage():
 6     print('-h help 
-i --ip address
-p --port number
')
 7 
 8 
 9 if __name__ == '__main__':
10     try:
11         options, args = getopt.getopt(sys.argv[1:], "hp:i:", ['help', "ip=", "port="])
12         for name, value in options:
13             if name in ('-h', '--help'):
14                 usage()
15             elif name in ('-i', '--ip'):
16                 print(value)
17             elif name in ('-p', '--port'):
18                 print(value)
19     except getopt.GetoptError:
20         usage()

在命令行中输入以下测试:

 1 D:wybpythonoldboy>python3 test.py -h
 2 -h help
 3 -i --ip address
 4 -p --port number
 5 
 6 D:wybpythonoldboy>python3 test.py -i 12.56.45.1 -p 90
 7 12.56.45.1
 8 90
 9 
10 D:wybpythonoldboy>python3 test.py --ip 12.56.45.1 --port 90
11 12.56.45.1
12 90

注:

sys.argv[1:]是引入命令行参数(文件名后的命令行参数)

定义命令行参数时,要先定义带'-'选项的参数,再定义带‘--’的参数

二、全局替换程序

需求:

写一个脚本允许用户按以下方式执行时既可以对指定文件内容进行全局替换python replace_script.py old_str new_str filename

并替换完毕后打印替换了多少处内容

实现1:  实现替换内容

 1 # __author__ = "wyb"
 2 # date: 2018/4/18
 3 
 4 # 需求:
 5 # 写一个脚本允许用户按以下方式执行时既可以对指定文件内容进行全局替换
 6 # python replace_script.py old_str new_str filename
 7 # 替换完毕后打印替换了多少处内容
 8 
 9 import getopt
10 import sys
11 
12 old_str = ""
13 new_str = ""
14 file_name = ""
15 
16 
17 def usage():
18     print('-h help 
-o --old old_str
-n --new new_str
-f --file filename')
19     exit()
20 
21 
22 def replace_str():
23     # 先替换到另外一个文件
24     f1 = open(file_name, "r", encoding="utf-8")
25     f2 = open('change_bak.txt', "w", encoding="utf-8")
26     # 读取要修改的文件
27     for line in f1:
28         if old_str in line:
29             line = line.replace(old_str, new_str)
30         f2.write(line)
31     f1.close()
32     f2.close()
33 
34     # 再写回
35     f1 = open(file_name, "w", encoding="utf-8")
36     f2 = open('change_bak.txt', "r", encoding="utf-8")
37     for line in f2:
38         f1.write(line)
39 
40     f1.close()
41     f2.close()
42 
43 
44 if __name__ == '__main__':
45     try:
46         options, args = getopt.getopt(sys.argv[1:], "ho:n:f:", ['help', "old=", "new=", "file="])
47         for name, value in options:
48             if name in ('-h', '--help'):
49                 usage()
50             elif name in ('-o', '--old'):
51                 old_str = value
52             elif name in ('-n', '--new'):
53                 new_str = value
54             elif name in ('-f', '--file'):
55                 file_name = value
56     except getopt.GetoptError:
57         usage()
58 
59     if old_str and new_str and file_name:
60         replace_str()

注: 当我们读取文件中内容后,如果想要修改文件中的某一行或者某一个位置的内容,在python中是没有办法直接实现的,如果想要实现这样的操作只能先把文件所有的内容全部读取出来,然后进行匹配修改后写入到新的文件中,最后把新文件中的内容写入旧文件

实现2:  实现替换内容并输出替换次数

 1 # __author__ = "wyb"
 2 # date: 2018/4/18
 3 import getopt
 4 import sys
 5 
 6 old_str = ""
 7 new_str = ""
 8 file_name = ""
 9 
10 
11 def usage():
12     print('-h help 
-o --old old_str
-n --new new_str
-f --file filename')
13     exit()
14 
15 
16 def replace_str():
17     count = 0
18     # 先替换到另外一个文件
19     f1 = open(file_name, "r", encoding="utf-8")
20     f2 = open('change_bak.txt', "w", encoding="utf-8")
21     # 读取要修改的文件
22     for line in f1:
23         if old_str in line:
24             count += line.count(old_str)
25             line = line.replace(old_str, new_str)
26         f2.write(line)
27     f1.close()
28     f2.close()
29 
30     # 再写回
31     f1 = open(file_name, "w", encoding="utf-8")
32     f2 = open('change_bak.txt', "r", encoding="utf-8")
33     for line in f2:
34         f1.write(line)
35 
36     f1.close()
37     f2.close()
38 
39     print("总共替换了%d个字符串" % count)
40 
41 
42 if __name__ == '__main__':
43     try:
44         options, args = getopt.getopt(sys.argv[1:], "ho:n:f:", ['help', "old=", "new=", "file="])
45         for name, value in options:
46             if name in ('-h', '--help'):
47                 usage()
48             elif name in ('-o', '--old'):
49                 old_str = value
50             elif name in ('-n', '--new'):
51                 new_str = value
52             elif name in ('-f', '--file'):
53                 file_name = value
54     except getopt.GetoptError:
55         usage()
56 
57     if old_str and new_str and file_name:
58         replace_str()

常见用法:

在字符串中寻找子串的出现个数-> s.count(str)

1 s = "666   你说我6不6?  666"
2 print(s.count("666"))
3 # 输出: 2
原文地址:https://www.cnblogs.com/wyb666/p/8877989.html