The examples in this article describe the use of sys.argv parameters in Python. Share to everyone for your reference. The specific analysis is as follows:
In the process of learning Python, I never understood the meaning of sys.argv[], though I knew it was a command line argument, but it was a bit of a blur.
Today, a good study of a, finally is Taichetaiwu.
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[]
Import Sys,osos.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[].
Import sysdef ReadFile (filename): #从文件中读出文件内容 ' Print a file to the standard output. ' f = file (filename) while true:line = F.readline () If Len (lines) = = 0:breakprint line, # Notice comma outputs each row of content F.close () # Scrip T starts from HEREif Len (SYS.ARGV) < 2:print ' No action specified. ' Sys.exit () if Sys.argv[1].startswith ('--'): option = S ys.argv[1][2:]# fetch sys.argv[1] but without the first and charactersif option = = ' Version ': #当命令行参数为--version, showing the revision number Prin T ' Version 1.2 ' elif option = = ' help ': #当命令行参数为--help When the content is displayed "This program prints files to the standard OUTPUT.A NY number of files can be specified. Options include:--version:prints The version number--help : Display This "" Else:print ' Unknown option. ' Sys.exi T () else:for filename in sys.argv[1:]: #当参数为文件名时, passing in ReadFile, reading its contents ReadFile (filename)
Save the program as sample.py. Let's verify that:
command line with parameters run: Sample.py–version output is: Version 1.2
command line with parameters run: Sample.py–help output is: This program prints files ...
In the same directory as sample.py, the new a.txt Notepad file is: Test argv; command line with parameters run: sample.py a.txt, the output is a.txt file content: Test argv, here can also take a few parameters, The program will output the contents of the parameter file successively.
Hopefully this article will help you with Python programming.