Sys.argv[] is used to get command line arguments, Sys.argv[0] represents the code itself file path, so the parameters starting from 1, the following two examples illustrate:
1. A simple example of using sys.argv[]:
The following is the sample1.py file:
[Python]View PlainCopy
- Import Sys,os
- Print SYS.ARGV
- Os.system (sys.argv[1])
Os.system ("Bash command") runs a shell command that directly displays and simulates a person's operation,
This example Os.system receive command line arguments, run parameter directives, cmd command line with parameters run Python sample1.py Notepad, will open the Notepad program.
2, this example is a concise Python tutorial, understand it after you understand sys.argv[].
The following is the sample.py file:
[Python]View PlainCopy
- #!/usr/bin/env python
- #_ *_ Coding:utf-8 _*_
- Import Sys
- def readfile (filename): #定义readfile函数 to read the contents of a file from a file
- "" " Print a file to the standardoutput. ' "'
- f = file (filename)
- while True:
- line = F.readline ()
- If Len (line) = = 0:
- Break
- print line, # notice comma output each row of content separately
- F.close ()
- # Script starts from here
- Print SYS.ARGV
- 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 and the characters
- if option = = ' version ': #当命令行参数为--version, display the revision number
- print ' Version 1.2 '
- elif option = = ' help ': when #当命令行参数为--help, the relevant helper content is displayed
- print " "
- Prints files to the standard output.
- Any number of the files can be specified.
- Options include:
- --version:prints the version number
- --help:display this " "
- Else:
- print ' Unknown option. '
- Sys.exit ()
- Else
- For filename in sys.argv[1:]: #当参数为文件名时, incoming ReadFile, read out its contents
- ReadFile (filename)
In the same directory as sample.py, create a new 3 Notepad file Test.txt,test1.txt,test2.txt, as follows:
Verify the sample.py as follows:
C:\users\91135\desktop>python sample.py
[' sample.py ']
No action specified.
C:\users\91135\desktop>python sample.py--help
[' sample.py ', '--help ']
Prints files to the standard output.
Any number of the files can be specified.
Options include:
--version:prints the version number
--help:display this Help
C:\users\91135\desktop>python sample.py--version
[' sample.py ', '--version ']
Version 1.2
C:\users\91135\desktop>python sample.py--ok
[' sample.py ', '--ok ']
Unknown option.
C:\users\91135\desktop>python sample.py Test.txt
[' sample.py ', ' test.txt ']
Hello python!
C:\users\91135\desktop>python sample.py test.txt test1.txt test2.txt
[' sample.py ', ' test.txt ', ' test1.txt ', ' test2.txt ']
Hello python!
Hello world!
Hello wahaha!
goodbye!
C:\users\91135\desktop>
Python sys.argv[] Usage