What is “argv”, and what does it do?

前端 未结 7 1681
耶瑟儿~
耶瑟儿~ 2020-11-30 04:36

argv

What on Earth is it!?

Edit: If you can, will you please write a line or two and explain how it works?

7条回答
  •  温柔的废话
    2020-11-30 04:52

    sys .argv will display the command line args passed when running a script or you can say sys.argv will store the command line arguments passed in python while running from terminal

    It stores the arguments in a list ds.

    sample usage: Create a file say: cmdlineargs.py and put the following in it:

    import sys
    print sys.argv 
    

    Now run the file in your terminal/cli :

    python cmdlineargs.py 
    

    or something like

    python cmdlineargs.py example example1
    

    Notice what happens now. Your script will print everything passed in your cmd line argument while you ran that script.

    Important to know:

    print len(sys.argv) #total arguments passed
    sys.argv[0] #this is your script name stored in sys.argv.
    print sys.argv #display all arguments passed
    sys.argv[0] #is the first argument passed, which is basically the filename.
    sys.argv #stores all cmd line args in a list ds
    

    You can look up each specific argument passed like this, probably:

    cmdLineArg = len(sys.argv)
    i=0
    for argv in sys.argv:
        if cmdLineArg<=len(sys.argv) :
            print "argument",i,"is", str(sys.argv[i])
            i=i+1
        else:
            print "Only script name in sys.argv"
    

    Sample result:

    Say you run the following in your terminal.

    python cmdlineargs.py example example1
    

    Your result should look something like:

    argument 0 is cmdlineargs.py
    argument 1 is example
    argument 2 is example1  
    

    Notice argument 0 is the same as the file name . Hope this was helpful.


    Thanks for the upvotes, improving my answer for the loop. A little more pythonian answer should look like this:

    i=0
    for argv in sys.argv:
        if cmdLineArg==1:
            print "Only script name in sys.argv"
        elif (cmdLineArg>1 and cmdLineArg<=len(sys.argv)):
            print "argument ",i,"is", str(argv)
            i=i+1
    print "total arguments passed:\t", totalargs
    

    I too am new to python so I had a habit of declaring i and j for traversing arrays. :)

提交回复
热议问题