Python main的命令行参数:sys.argv

自己写了一个功能函数方便自己使用,突然意识到需要用到sys.argv来传参,于是记录一下。

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”中)“,结果如下:

  1. 原文件:
    这里写图片描述
  2. 命令行结果:
    这里写图片描述
    可以看到输出的传入参数的第一个参数是我们源程序文件的绝对地址
  3. 执行结果:
    这里写图片描述

所以,从以上运行结果,可以知道在命令行中传参时,第一个参数是我们的源程序的绝对地址,从第二个参数(index是从1开始)开始是传入的参数。

  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值