Example Analysis of sys. argv parameter usage in python
This example describes how to use the sys. argv parameter in python. Share it with you for your reference. The specific analysis is as follows:
In the course of learning python, I have never understood the meaning of sys. argv []. Although I know it is a command line parameter, I still feel confused.
Today, I learned a little better and finally realized it.
Sys. argv [] is used to obtain the command line parameters. sys. argv [0] indicates the file path of the Code. Therefore, the parameter starts from 1. The following two examples illustrate:
1. Use a simple instance of sys. argv []
?
1 2 |
Import sys, OS OS. system (sys. argv [1]) |
In this example, OS. system receives command line parameters, runs parameter commands, and saves them as sample1.py. The command line runs sample1.py notepad with parameters, and opens the notepad program.
2. This example is a concise python tutorial. After you understand it, you will understand sys. argv.
?
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
Import sys Def readfile (filename): # Read the file content from the file '''Print a file to the standard output .''' F = file (filename) While True: Line = f. readline () If len (line) = 0: Break Print line, # notice comma output the content of each line separately F. close () # Script starts from here If len (sys. argv) <2: Print 'no action specified .' Sys. exit () If sys. argv [1]. startswith ('--'): Option = sys. argv [1] [2:] # Fetch sys. argv [1] but without the first two characters If option = 'version': # When the command line parameter is -- version, the version number is displayed. Print 'version 1.2' Elif option = 'help': # The help content is displayed when the command line parameter is -- help. Print '''" This program prints files to the standard output. Any number of files can be specified. Options include: -- Version: Prints the version number -- Help: Display this help ''' Else: Print 'unknown option .' Sys. exit () Else: For filename in sys. argv [1:]: # When the parameter is a file name, input readfile to read its content. Readfile (filename) |
Save the program as sample. py. Let's verify it:
Run the command line with parameters: sample. py-version. The output result is: version 1.2.
Run the command line with parameters: sample. py-help. The output result is: This program prints files ......
In the same directory as sample.py, the.txt notepad file is created with the following content: test argv. Run the command line with parameters: sample. py a.txt, the output result is a.txt file content: test argv. Here you can also include several more parameters. The program will output the parameter file content successively.
I hope this article will help you with Python programming.