Python main的命令行参数:sys.argv
2016-06-13 21:17
330 查看
自己写了一个功能函数方便自己使用,突然意识到需要用到sys.argv来传参,于是记录一下。
python使用sys.argv来传参。例如:我自己写了一个字符替换的python程序replace.py。
可以看到,我在每一次初始化时输出了传入参数的第一个参数,那么我在命令中就执行“replace.py : -.-(将”content.txt”文件中的”:”替换为”-.-“,并保存在”result.txt”中)“,结果如下:
原文件:
命令行结果:
可以看到输出的传入参数的第一个参数是我们源程序文件的绝对地址
执行结果:
所以,从以上运行结果,可以知道在命令行中传参时,第一个参数是我们的源程序的绝对地址,从第二个参数(index是从1开始)开始是传入的参数。
python使用sys.argv来传参。例如:我自己写了一个字符替换的python程序replace.py。
# -*- coding:utf-8 -*- import sys class replace: def __init__(self, argv): ''' source: the old chars destination: the new chars ''' print '"'+argv[0]+'"' if len(argv) == 5: self.fileName = argv[1] self.outFile = argv[2] self.source = argv[3] self.destination = argv[4] elif len(argv) == 4: self.fileName = argv[1] self.outFile = argv[2] self.source = argv[3] self.destination = '' elif len(argv) == 3: self.fileName = "content.txt" self.outFile = "result.txt" self.source = argv[1] self.destination = argv[2] elif len(argv) == 2: self.fileName = "content.txt" self.outFile = "result.txt" self.source = argv[1] self.destination = '' elif len(argv) == 1: self.fileName = "content.txt" self.outFile = "result.txt" self.source = ":" self.destination = '' def setSource(self, source): self.source = source def setDestination(self, destination): self.destination = destination def replaceContent(self): content = open(self.fileName, 'r') result = open(self.outFile, 'w') for line in content.readlines(): print >> result, line.replace(self.source, self.destination) result.close() content.close() def replaceContentPos(self, positions): pos = 1 start = 0 content = open(self.fileName, 'r') result = open(self.outFile, 'w') for line in content.readlines(): if (pos == positions[start]): print >> result, line.replace(self.source, self.destination) start += 1 pos += 1 result.close() content.close() if (__name__ == '__main__'): mine = replace(sys.argv) mine.replaceContent()
可以看到,我在每一次初始化时输出了传入参数的第一个参数,那么我在命令中就执行“replace.py : -.-(将”content.txt”文件中的”:”替换为”-.-“,并保存在”result.txt”中)“,结果如下:
原文件:
命令行结果:
可以看到输出的传入参数的第一个参数是我们源程序文件的绝对地址
执行结果:
所以,从以上运行结果,可以知道在命令行中传参时,第一个参数是我们的源程序的绝对地址,从第二个参数(index是从1开始)开始是传入的参数。
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例
- Python 七步捉虫法