sys.argv[1] meaning in script

后端 未结 9 1409
野趣味
野趣味 2020-11-22 11:02

I\'m currently teaching myself Python and was just wondering (In reference to my example below) in simplified terms what the sys.argv[1] represents. Is it simpl

相关标签:
9条回答
  • 2020-11-22 11:45

    sys.argv is a attribute of the sys module. It says the arguments passed into the file in the command line. sys.argv[0] catches the directory where the file is located. sys.argv[1] returns the first argument passed in the command line. Think like we have a example.py file.

    example.py

    import sys # Importing the main sys module to catch the arguments
    print(sys.argv[1]) # Printing the first argument
    

    Now here in the command prompt when we do this:

    python example.py
    

    It will throw a index error at line 2. Cause there is no argument passed yet. You can see the length of the arguments passed by user using if len(sys.argv) >= 1: # Code. If we run the example.py with passing a argument

    python example.py args
    

    It prints:

    args
    

    Because it was the first arguement! Let's say we have made it a executable file using PyInstaller. We would do this:

    example argumentpassed
    

    It prints:

    argumentpassed
    

    It's really helpful when you are making a command in the terminal. First check the length of the arguments. If no arguments passed, do the help text.

    0 讨论(0)
  • 2020-11-22 11:52

    To pass arguments to your python script while running a script via command line

    python create_thumbnail.py test1.jpg test2.jpg

    here, script name - create_thumbnail.py, argument 1 - test1.jpg, argument 2 - test2.jpg

    With in the create_thumbnail.py script i use

    sys.argv[1:]
    

    which give me the list of arguments i passed in command line as ['test1.jpg', 'test2.jpg']

    0 讨论(0)
  • 2020-11-22 11: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.

    Just try this:

    import sys
    print sys.argv
    

    argv stores all the arguments passed in a python list. The above will print all arguments passed will running the script.

    Now try this running your filename.py like this:

    python filename.py example example1
    

    this will print 3 arguments in a list.

    sys.argv[0] #is the first argument passed, which is basically the filename. 
    

    Similarly, argv1 is the first argument passed, in this case 'example'

    A similar question has been asked already here btw. Hope this helps!

    0 讨论(0)
提交回复
热议问题