Python main的命令行参数(sys.argv)

自己写了一个功能函数方便自己使用,突然意识到需要用到sys.argv来传参,于是记录一下。
python使用sys.argv来传参。例如:我自己写了一个字符替换的python程序replace.py。

# -*- coding:utf-8 -*- import sysclass 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 = sourcedef setDestination(self, destination): self.destination = destinationdef 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()

【Python main的命令行参数(sys.argv)】可以看到,我在每一次初始化时输出了传入参数的第一个参数,那么我在命令中就执行“replace.py : -.-(将”content.txt”文件中的”:”替换为”-.-“,并保存在”result.txt”中)“,结果如下:
  1. 原文件:
    Python main的命令行参数(sys.argv)
    文章图片
  2. 命令行结果:
    Python main的命令行参数(sys.argv)
    文章图片

    可以看到输出的传入参数的第一个参数是我们源程序文件的绝对地址
  3. 执行结果:
    Python main的命令行参数(sys.argv)
    文章图片
所以,从以上运行结果,可以知道在命令行中传参时,第一个参数是我们的源程序的绝对地址,从第二个参数(index是从1开始)开始是传入的参数。

    推荐阅读