Sys.argv[] is used to get command-line arguments,sys.argv[0] represents the code itself file path, so the parameter starts at 1, The following two examples illustrate:
1, using A simple example of sys.argv[],
[Python] View plain copy
Import Sys,os
Os.system (Sys.argv[1])
This example os.system receive command line arguments, run parameter directives, save as sample1.py, command line with parameters run sample1.py notepad, will open the Notepad program.
2, this example is a concise python tutorial, understand it after you understand sys.argv[] .
[Python] View plain copy
Import Sys
def readfile (filename): # Read the contents of a file from a 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 each row of content 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 and the characters
if option = = ' version ': # when the command line argument is --version, the version number is displayed
print ' Version 1.2 '
elif option = = ' help ': # when the command-line argument is --help , the relevant helper content is displayed
Print ""/
Prints files to the StandardOutput.
Any number of the files can be specified.
Options include:
--version:prints the version number
--help:display thishelp ""
Else
print ' Unknown option. '
Sys.exit ()
Else
For filename in sys.argv[1:]: # When the argument is a file name, pass in the ReadFileand read its contents
ReadFile (filename)
the Save program is sample.py. Let's verify that:
1) command line with parameters run:sample.py –version output is:version1.2
2) command line with parameters run:sample.py – The Help output is:thisprogram prints files...
3) in the same directory as sample.py, create a new a.txt Notepad file with the content:test argv; command line with parameters run:sample.py a.txt, The output is a.txt file content:test argv, here can also take more than a few parameters, the program will output the parameters of the file content.
Python sys.argv