Python command-line arguments sys.argv[]

Source: Internet
Author: User
Tags readfile readline

Learn the C language when you do not understand the use of command-line parameters, in the learning Pyton, and encountered the command line parameters, here a little study, a little understanding of some here to make a record convenient back review review.

Sys.argv[] is used to get command line arguments, Sys.argv[0] represents the absolute path of the code file, so the remaining parameters start from 1, the following two examples illustrate:

1.

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[].

1. Import SYS 2.        def readfile (filename): #从文件中读出文件内容, this is the function that is called when the parameter is passed to the file name de 3.  ' Print a file to the standard output. '        4. F = file (filename) #打开文件, here is the same as the open effect 5.            While true:6. Line = F.readline () #读取每行信息7.                If Len (line) = = 0:8.            Break 9.        Print line, # Notice comma outputs each row of content 10 respectively.    F.close () 11.    # Script starts from here is the entry for the program, first to determine if there is a command line parameter passed less than two that is no command line parameters of 12.        If Len (SYS.ARGV) < 2:13.  print ' No action specified. '    Sys.exit () 15.        If Sys.argv[1].startswith ('---'): #判断命令行参数是否是以--Start, if it is the parameter of the relevant command, if it is not the file name is 16. option = sys.argv[1][2:] #这是一个二维数组, put argv[1] This parameter's subscript is [2] that is, the third character starts until the end of the string
#复制给option if it is--help, then option is help17. # fetch SYS.ARGV[1] But without the first and characters 18. if option = = ' Version ': #当命令行参数为--version, showing the revision number 19. print ' Version 1.2 ' 20. elif option = = ' help ': When #当命令行参数为--help, the relevant content and the relevant contents of the printed note 21. print '/22. Prints files to the standard output. All number of files can be specified. Options include:25. --version:prints the version number 26. --help:display this "" 27. else: #否则打印不知道的命令28. print ' Unknown option. ' Sys.exit () 30. else: #如果命令行参数不是以--The format begins, then the file is executed, so the West section Code 31. For filename in sys.argv[1:]: #当参数为文件名时, pass in the ReadFile, read its contents 32. ReadFile (filename)

Save the program as sample.py. Let's verify that:

1) command line with parameters run: Sample.py–-version output is: Version 1.2

2) command line with parameters run: Sample.py–-help output is: This program 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 a few more parameters, The program will output the contents of the parameter file successively.

1 #coding: Utf-8 2 "3 Created on August 10, 2015 4  5 @author: YJ 6" ' 7 import sys 8 def  skip_header (R): 9     "' Sk IP the Reader in Reader R,and return the first real piece of data.     #Read the description line and then the comment lines. Read the description and comment lines one by one     , Row =r.readline ()     print line13     While Line.startswith (' # '): +         line=r.readline ()    #跳到下一行15     #Now Line contains the first Raal piece of data.16     return Line def process_file (R): "     Read and print open reader R."     #Find and print piece of data.     Line=skip_header (R). Strip ()     print Line22 #Read The rest of the data.23 for line in     r:24         Line=line.strip ()         print line26 if __name__== "__main__":     print "Start"     input_file=open ( Sys.argv[1], ' R ')     Process_file (input_file)-     input_file.close ()

3, the above example uses a function startswith ()

Function: StartsWith ()

Function: Determines whether a string begins with a specified character or substring

First, function description
Syntax: String.startswith (str, Beg=0,end=len (String))
or String[beg:end].startswith (str)

Parameter description:
String: The character being detected
STR: The specified character or substring. (tuples can be used, matching each)
Beg: Set the starting position for string detection (optional)
End: Sets the end position of the string detection (optional)
If there are parameters beg and end, check within the specified range, otherwise check the entire string

return value
Returns True if a string is detected, otherwise false. The default null character is True

Function parsing: Returns True if string strings are starting with STR, otherwise false

Instance:

s = ' Hello good boy doiido ' Print s.startswith (' h ') print s.startswith (' hel ') print s.startswith (' h ', 4) print S.startswith ( ' Go ', 6,8) #匹配空字符集print s.startswith (') #匹配元组print s.startswith ((' t ', ' B ', ' h ')) Common environment: used if to determine if S.startswith (' Hel '):    print "You is Right" else:    print "Wrang"

4, the above program used the strip () function below a brief introduction

Note: The Strip () function itself does not affect the contents of the original string, but only a new string, regardless of the original string

Function prototypes

statement: s as a string, RM the sequence of characters to be deleted

S.strip (RM) Remove the characters from the beginning and end of the S string in the RM delete sequence

S.lStrip (RM) Delete the characters at the beginning of the S string in the RM delete sequence

S.rStrip (RM) Delete the character at the end of the S string in the RM delete sequence

Attention:

A. when rm is empty, the default is to remove the white space character (including ' \ n ', ' \ R ', ' \ t ', ')

For example:

Copy the code code as follows:

>>> a = ' 123 '
>>> A.strip ()
' 123 '
>>> a= ' \T\TABC '
' ABC '
>>> a = ' sdff\r\n '
>>> A.strip ()
' SDFF '

B. The RM delete sequence here is deleted as long as the character on the edge (beginning or end) is within the delete sequence.

For example:

Copy the code code as follows:

>>> a = ' 123abc '
>>> A.strip (' 21 ')
' 3abc ' turns out to be the same
>>> A.strip (' 12 ')
' 3abc '

5. function split ()

Description
Python There is no character type in the argument, only the string, the character here is a string containing only one character!!!
The reason for writing here is just for the convenience of understanding, that's all.

A, divide by a character such as "."

1 str = ' www.baidu.com ' 2 #这里的str. Split ('. ') To a new string that does not affect the original str string 3 str1 = Str.split ('. ') 4 5 Print str16 print STR7 8 #结果为 [' www ', ' Baidu ', ' com ']   ' www.baidu.com '

b, divided by a character, and divided n times. If you press '. ' Split 1 times

1 str = (' www.google.com ') 2 print str3 str_split = Str.split ('. ', 1) 4 print str_split5 #结果: [' www ', ' google.com ']

C, split by a character (or string), and divide n times, and assign the completed string (or character) of the partition to a new (n+1) variable. (Note: See opening instructions)

such as: Press '. ' Splits the character, splits it 1 times, and assigns the split string to 2 variables respectively STR1,STR2

1 URL = (' www.google.com ') 2 str1, str2 = Url.split ('. ', 1) 3 print str14 print Str25 6 #结果为: str1:www str2:google.com

Python command-line arguments sys.argv[]

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.