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 test_sys_arg.py. 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.

Save below code in file test_sys_arg.py file.

# first import built-in sys module.
import sys

def sys_argv_example():

    # 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(str(i))

        #print(tmp_argv)

        print('argv ' + str(i) + ' = ' + tmp_argv)            


if __name__ == "__main__":
    
    sys_argv_example()

Open a terminal and goto above python file sved directory, then run python test_sys_arg.pylike below.

C:\WorkSpace>python test_sys_arg.py test
there are 2 arguments.
0
test_sys_arg.py
argv 0 = test_sys_arg.py
1
test
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.

Save below python source code in file test_sys_arg.py file.

# first import built-in sys module.
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:

        break

      print(line)

    # print a separator line when read out all file content.
    print('******************* read file ' + file_name + ' end ***************************')


def read_file_main():

    # 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[_])

            read_file(sys.argv[_])
        else:
           
           print('The python file is: ', sys.argv[_], ' without arguments.')
            

if __name__ == "__main__":

    read_file_main()

Create a file text.txt and input some text data. Save it in the same folder of test_sys_arg.py file.

Open a terminal and goto above python file sved directory, then run python test_sys_arg.py test.txtlike below.

The python file is:  d:/Work/python-courses/python-basic/test_sys_arg.py  without arguments.

3. Example Demo Video.

Leave a Comment

Your email address will not be published. Required fields are marked *

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