python read parameters from the command line

sys.argv [1] is read from the command line representative of the first parameter, sys.argv [2] representative of the second parameter read from the command line, and so on back

Note sys.argv [n] is read str type, so it needs to perform digital conversion type! ! !

In the class of a function of the shape parameter self must add! ! !

code show as below:

import sys,random

class Person:
    sex='男'#属性可直接定义
    def __init__(self,name,age): #构造函数
        self.name=name
        self.age=age
        
    def say_hi(self): #self参数一定要加!!!
        print('hello,I\'m',self.name)
        
    def fun(self,n,m):
        print('m=',m)
        for i in range(n):
            #randrange() 方法返回指定递增基数集合中的一个随机数,基数默认值为1。
            #前闭后开
            print(random.randrange(100))
        return


if __name__=='__main__':
    p=Person('函宝宝',22)#定义对象初始化
    p.say_hi()
    print(p.sex)
    n=int(sys.argv[1])#从命令行读取一个参数赋给n,是str类型所以需要转换成int型
    m=int(sys.argv[2])
    p.fun(n,m)
    

operation result:

Format: Python Parameter File 1 [Parameter 2 Parameter 3 Parameter ... n]

Switch to the directory where the file execution

Or directly to an absolute path (the same effect)

If the problem is given as follows path, attention switches to the file's directory!

 

Published 81 original articles · won praise 91 · views 10000 +

Guess you like

Origin blog.csdn.net/weixin_44593822/article/details/103392262