How To Use sys.argv[] In Python

sys.argv[] is used to get python command line arguments. sys.argv[0] ‘s value is the file path of the python source code file that is running. For example, if you run python test_sys_arg.pyin a terminal, then sys.argv[0]‘s value is This article will give you two example about how to use sys.argv[] to get command line arguments in python source code.

1. sys.argv[] Example.

Below python file will print out all elements in sys.argv[] list.

  1. Save below code in file file.
    # first import built-in sys module.
    import sys
    # get command line argument length.
    argv_len = len(sys.argv)
    print('there are ' + str(argv_len) + ' arguments.')
    # loop in all arguments.
    for i in range(argv_len):
      tmp_argv = sys.argv[i]
      # print out argument index and value.
      print('argv ' + str(i) + ' = ' + tmp_argv)
  2. Open a terminal and goto above python file sved directory, then run python test_sys_arg.pylike below.
    C:\WorkSpace>python test
    there are 2 arguments.
    argv 0 =
    argv 1 = test

2. Read File Example.

Below example will read file content and print it in console, and the file name is passed from the sys.argv[] arguments.

  1. Save below python source code in file file.
    import sys
    ''' This function will read out a file content and print the content to standard output.'''
    def read_file(file_name):
      # open file object use python with statement.
      with open(file_name) as file:
        # loop in the file and read each line.
        while True:
          line = file.readline()
          if len(line) == 0:
        # print a separator line when read out all file content.
        print('******************* read file ' + file_name + ' end ***************************')
    # get argv length.
    argv_len = len(sys.argv)
    # loop in the python command arguments list, _ is a local variable which will be dropped after use.
    for _ in range(argv_len):
      # the first python command argument is this .py file it's self.
      if(_ >= 0):
        # print out argument info.
        print('Argument ' + str(_ + 1) + ' : ' + sys.argv[_])
  2. Create a file text.txt and input some text data. Save it in the same folder of file.
  3. Open a terminal and goto above python file sved directory, then run python test.txtlike below.
    C:\WorkSpace>python test.txt
    Argument 1 :
    ******************* read file end ***************************
    Argument 2 : test.txt
    ******************* read file test.txt end ***************************
0 0 vote
Article Rating
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Would love your thoughts, please comment.x