Python命令行参数sys.argv[]

 

 

学习C语言的时候就没弄明白命令行参数的用法,在学习Pyton 的时候又遇到了命令行参数,在这里稍微学习了一下,稍微明白了一些在这里做个记录方便后面回顾复习。

Sys.argv[]是用来获取命令行参数的,sys.argv[0]表示代码文件绝对路径,所以所以其余参数从1开始,以下两个例子说明:

 

1、

import sys,os 
os.system(sys.argv[1])

这个例子os.system接收命令行参数,运行参数指令,保存为sample1.py,命令行带参数运行sample1.py notepad,将打开记事本程序。

 

2、这个例子是简明python教程上的,明白它之后你就明白sys.argv[]了。

复制代码
1.    import sys  
2.    def readfile(filename):  #从文件中读出文件内容  ,这是被调函数但被传参数为文件名de时候调用该函数
3.        '''''Print a file to the standard output.'''  
4.        f = file(filename)  #打开文件,这里和open效果一样
5.        while True:  
6.            line = f.readline()  #读取每行信息
7.            if len(line) == 0:  
8.                break  
9.            print line, # notice comma  分别输出每行内容  
10.        f.close()  
11.    # Script starts from here  这里才是程序的入口,先判断是否有命令行参数传入小于二也就是没有命令行参数了
12.    if len(sys.argv) < 2:  
13.        print 'No action specified.'  
14.        sys.exit()  
15.    if sys.argv[1].startswith('--'):  #判断命令行参数是否是以--开始的,如果是则是相关命令的参数,如果不是就是文件名了
16.        option = sys.argv[1][2:]     #这是一个二维数组,把argv[1]这个参数的下标为[2]即第三个字符开始直到结束的字符串
                        #复制给option 如果是--help,则这之后option为help 17. # fetch sys.argv[1] but without the first two characters 18. if option == 'version': #当命令行参数为-- version,显示版本号 19. print 'Version 1.2' 20. elif option == 'help': #当命令行参数为--help时,显示相关帮助内容 及打印注释的相关内容 21. print '''''/ 22. This program prints files to the standard output. 23. Any number of files can be specified. 24. Options include: 25. --version : Prints the version number 26. --help : Display this help''' 27. else: #否则打印不知道的命令 28. print 'Unknown option.' 29. sys.exit() 30. else: #如果命令行参数不是以--格式开始的,那么就是文件了所以执行西段代码 31. for filename in sys.argv[1:]: #当参数为文件名时,传入readfile,读出其内容 32. readfile(filename)
复制代码

保存程序为sample.py.我们验证一下:

1)       命令行带参数运行:sample.py –-version  输出结果为:version 1.2

2)       命令行带参数运行:sample.py –-help  输出结果为:This program prints files……

3)       在与sample.py同一目录下,新建a.txt的记事本文件,内容为:test argv;命令行带参数运行:sample.py a.txt,输出结果为a.txt文件内容:test argv,这里也可以多带几个参数,程序会先后输出参数文件内容。

复制代码
 1 #coding:utf-8
 2 '''
 3 Created on 2015年8月10日
 4 
 5 @author: yj
 6 '''
 7 import sys
 8 def  skip_header(r):
 9     '''Skip the reader in reader r,and return the first real piece of data.'''
10     #Read the description line and then the comment lines.读取描述和注释行
11     line =r.readline()
12     print line
13     while line.startswith('#'):
14         line=r.readline()    #跳到下一行
15     #Now line contains the first raal piece of data.
16     return line 
17 def process_file(r):
18     '''Read and print open reader r.'''
19     #Find and print piece of data.
20     line=skip_header(r).strip()
21     print line
22     #Read the rest of the data.
23     for line in r:
24         line=line.strip()
25         print line
26 if __name__=="__main__":
27     print "start"
28     input_file=open(sys.argv[1],'r')
29     process_file(input_file)
30     input_file.close()
复制代码

 3、上面的例子用到了一个函数startswith()

函数:startswith()

作用:判断字符串是否以指定字符或子字符串开头

一、函数说明
语法:string.startswith(str, beg=0,end=len(string))
      或string[beg:end].startswith(str)
 
参数说明:
string:  被检测的字符串
str:      指定的字符或者子字符串。(可以使用元组,会逐一匹配)
beg:    设置字符串检测的起始位置(可选)
end:    设置字符串检测的结束位置(可选)
如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查

返回值
如果检测到字符串,则返回True,否则返回False。默认空字符为True

函数解析:如果字符串string是以str开始,则返回True,否则返回False

实例:

复制代码
s = 'hello good boy doiido'

print s.startswith('h')

print s.startswith('hel')

print s.startswith('h',4)

print s.startswith('go',6,8)
#匹配空字符集
print s.startswith('')
#匹配元组
print s.startswith(('t','b','h'))

常用环境:用于if判断
if s.startswith('hel'):
    print "you are right"
else:
    print "you are wrang"
复制代码

4、上面的程序用到了strip()函数下面简单介绍一下

注意:strip()函数本身并不影响原来字符串的内容,得到的仅仅是一个新的字符串,与原来的字符串无关

函数原型

声明:s为字符串,rm为要删除的字符序列

s.strip(rm)        删除s字符串中开头、结尾处,位于 rm删除序列的字符

s.lstrip(rm)       删除s字符串中开头处,位于 rm删除序列的字符

s.rstrip(rm)      删除s字符串中结尾处,位于 rm删除序列的字符

注意:

a. rm为空时,默认删除空白符(包括'\n', '\r',  '\t',  ' ')

例如:

复制代码 代码如下:

>>> a = '     123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff' 

b.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。

例如 : 

复制代码 代码如下:

>>> a = '123abc'
>>> a.strip('21')
'3abc'   结果是一样的
>>> a.strip('12')
'3abc'

 5、函数split()

说明:
Python中没有字符类型的说法,只有字符串,这里所说的字符就是只包含一个字符的字符串!!!
这里这样写的原因只是为了方便理解,仅此而已。

a、按照某个字符分割如“."

复制代码
1 str = 'www.baidu.com'
2 #这里的str.split('.')的到的是新的字符串,并不影响原来的str字符串
3 str1 = str.split('.')
4 
5 print str1
6 print str
7 
8 #结果为['www','baidu','com']   'www.baidu.com'
复制代码

b、按某一个字符分割,且分割n次。如按‘.’分割1次

1 str = ('www.google.com')
2 print str
3 str_split = str.split('.',1)
4 print str_split
5 #结果:['www','google.com']

c、按某一字符(或字符串)分割,且分割n次,并将分割的完成的字符串(或字符)赋给新的(n+1)个变量。(注:见开头说明)

如:按‘.’分割字符,且分割1次,并将分割后的字符串分别赋给2个变量str1,str2

复制代码
1 url = ('www.google.com')
2 str1, str2 = url.split('.', 1)
3 print str1
4 print str2
5 
6 #结果为:str1:www str2:google.com
复制代码

学习C语言的时候就没弄明白命令行参数的用法,在学习Pyton 的时候又遇到了命令行参数,在这里稍微学习了一下,稍微明白了一些在这里做个记录方便后面回顾复习。

Sys.argv[]是用来获取命令行参数的,sys.argv[0]表示代码文件绝对路径,所以所以其余参数从1开始,以下两个例子说明:

 

1、

import sys,os 
os.system(sys.argv[1])

这个例子os.system接收命令行参数,运行参数指令,保存为sample1.py,命令行带参数运行sample1.py notepad,将打开记事本程序。

 

2、这个例子是简明python教程上的,明白它之后你就明白sys.argv[]了。

复制代码
1.    import sys  
2.    def readfile(filename):  #从文件中读出文件内容  ,这是被调函数但被传参数为文件名de时候调用该函数
3.        '''''Print a file to the standard output.'''  
4.        f = file(filename)  #打开文件,这里和open效果一样
5.        while True:  
6.            line = f.readline()  #读取每行信息
7.            if len(line) == 0:  
8.                break  
9.            print line, # notice comma  分别输出每行内容  
10.        f.close()  
11.    # Script starts from here  这里才是程序的入口,先判断是否有命令行参数传入小于二也就是没有命令行参数了
12.    if len(sys.argv) < 2:  
13.        print 'No action specified.'  
14.        sys.exit()  
15.    if sys.argv[1].startswith('--'):  #判断命令行参数是否是以--开始的,如果是则是相关命令的参数,如果不是就是文件名了
16.        option = sys.argv[1][2:]     #这是一个二维数组,把argv[1]这个参数的下标为[2]即第三个字符开始直到结束的字符串
                        #复制给option 如果是--help,则这之后option为help 17. # fetch sys.argv[1] but without the first two characters 18. if option == 'version': #当命令行参数为-- version,显示版本号 19. print 'Version 1.2' 20. elif option == 'help': #当命令行参数为--help时,显示相关帮助内容 及打印注释的相关内容 21. print '''''/ 22. This program prints files to the standard output. 23. Any number of files can be specified. 24. Options include: 25. --version : Prints the version number 26. --help : Display this help''' 27. else: #否则打印不知道的命令 28. print 'Unknown option.' 29. sys.exit() 30. else: #如果命令行参数不是以--格式开始的,那么就是文件了所以执行西段代码 31. for filename in sys.argv[1:]: #当参数为文件名时,传入readfile,读出其内容 32. readfile(filename)
复制代码

保存程序为sample.py.我们验证一下:

1)       命令行带参数运行:sample.py –-version  输出结果为:version 1.2

2)       命令行带参数运行:sample.py –-help  输出结果为:This program prints files……

3)       在与sample.py同一目录下,新建a.txt的记事本文件,内容为:test argv;命令行带参数运行:sample.py a.txt,输出结果为a.txt文件内容:test argv,这里也可以多带几个参数,程序会先后输出参数文件内容。

复制代码
 1 #coding:utf-8
 2 '''
 3 Created on 2015年8月10日
 4 
 5 @author: yj
 6 '''
 7 import sys
 8 def  skip_header(r):
 9     '''Skip the reader in reader r,and return the first real piece of data.'''
10     #Read the description line and then the comment lines.读取描述和注释行
11     line =r.readline()
12     print line
13     while line.startswith('#'):
14         line=r.readline()    #跳到下一行
15     #Now line contains the first raal piece of data.
16     return line 
17 def process_file(r):
18     '''Read and print open reader r.'''
19     #Find and print piece of data.
20     line=skip_header(r).strip()
21     print line
22     #Read the rest of the data.
23     for line in r:
24         line=line.strip()
25         print line
26 if __name__=="__main__":
27     print "start"
28     input_file=open(sys.argv[1],'r')
29     process_file(input_file)
30     input_file.close()
复制代码

 3、上面的例子用到了一个函数startswith()

函数:startswith()

作用:判断字符串是否以指定字符或子字符串开头

一、函数说明
语法:string.startswith(str, beg=0,end=len(string))
      或string[beg:end].startswith(str)
 
参数说明:
string:  被检测的字符串
str:      指定的字符或者子字符串。(可以使用元组,会逐一匹配)
beg:    设置字符串检测的起始位置(可选)
end:    设置字符串检测的结束位置(可选)
如果存在参数 beg 和 end,则在指定范围内检查,否则在整个字符串中检查

返回值
如果检测到字符串,则返回True,否则返回False。默认空字符为True

函数解析:如果字符串string是以str开始,则返回True,否则返回False

实例:

复制代码
s = 'hello good boy doiido'

print s.startswith('h')

print s.startswith('hel')

print s.startswith('h',4)

print s.startswith('go',6,8)
#匹配空字符集
print s.startswith('')
#匹配元组
print s.startswith(('t','b','h'))

常用环境:用于if判断
if s.startswith('hel'):
    print "you are right"
else:
    print "you are wrang"
复制代码

4、上面的程序用到了strip()函数下面简单介绍一下

注意:strip()函数本身并不影响原来字符串的内容,得到的仅仅是一个新的字符串,与原来的字符串无关

函数原型

声明:s为字符串,rm为要删除的字符序列

s.strip(rm)        删除s字符串中开头、结尾处,位于 rm删除序列的字符

s.lstrip(rm)       删除s字符串中开头处,位于 rm删除序列的字符

s.rstrip(rm)      删除s字符串中结尾处,位于 rm删除序列的字符

注意:

a. rm为空时,默认删除空白符(包括'\n', '\r',  '\t',  ' ')

例如:

复制代码 代码如下:

>>> a = '     123'
>>> a.strip()
'123'
>>> a='\t\tabc'
'abc'
>>> a = 'sdff\r\n'
>>> a.strip()
'sdff' 

b.这里的rm删除序列是只要边(开头或结尾)上的字符在删除序列内,就删除掉。

例如 : 

复制代码 代码如下:

>>> a = '123abc'
>>> a.strip('21')
'3abc'   结果是一样的
>>> a.strip('12')
'3abc'

 5、函数split()

说明:
Python中没有字符类型的说法,只有字符串,这里所说的字符就是只包含一个字符的字符串!!!
这里这样写的原因只是为了方便理解,仅此而已。

a、按照某个字符分割如“."

复制代码
1 str = 'www.baidu.com'
2 #这里的str.split('.')的到的是新的字符串,并不影响原来的str字符串
3 str1 = str.split('.')
4 
5 print str1
6 print str
7 
8 #结果为['www','baidu','com']   'www.baidu.com'
复制代码

b、按某一个字符分割,且分割n次。如按‘.’分割1次

1 str = ('www.google.com')
2 print str
3 str_split = str.split('.',1)
4 print str_split
5 #结果:['www','google.com']

c、按某一字符(或字符串)分割,且分割n次,并将分割的完成的字符串(或字符)赋给新的(n+1)个变量。(注:见开头说明)

如:按‘.’分割字符,且分割1次,并将分割后的字符串分别赋给2个变量str1,str2

复制代码
1 url = ('www.google.com')
2 str1, str2 = url.split('.', 1)
3 print str1
4 print str2
5 
6 #结果为:str1:www str2:google.com
复制代码

猜你喜欢

转载自www.cnblogs.com/hellangels333/p/9222238.html