Python processing command-line arguments

Source: Internet
Author: User
Tags stdin

1. Save the command-line arguments in the list, note that argv[0] is the name of the program itself:

Import Sysprint (SYS.ARGV)                                                       print (sys.argv[1])

Python argv.py localhost 3306
[' argv.py ', ' localhost ', ' 3306 ']
localhost

2. Use Sys.stdin and fileinput to read the standard input and print the pipeline in the terminal-like shell

Import sys for line in      Sys.stdin:print (line,end= "")   

can be typed as a shell script, with standard input to the program

Python read_stdin.py </etc/passwd

Python read_stdin.py-

CAT/ETC/PASSWD |python read_stdin.py

Save standard input in a list

Import Sysdef get_content ():                                                         return Sys.stdin.readlines () print (Get_content ())

Python readlines_stdin.py <test/1.txt
[' hello\n ', ' world\n ']

3. Read standard input with Fileinput

#/usr/bin/env python#coding=utf-8                                                         Import fileinputfor line in Fileinput.input ():     print (line,end= "")

Python file_input1.py/etc/passwd

Python file_input1.py </etc/passwd

Python file_input1.py/etc/passwd/etc/my.cnf

Common methods of Fileinput:

#!/usr/bin/pythonfrom __future__ import print_functionimport fileinputfor line in Fileinput.input ():    meta = [ Fileinput.filename (), Fileinput.fileno (), Fileinput.filelineno (),            fileinput.isfirstline (), Fileinput.isstdin ( )]    print (*meta, end= "")
Print () print (line, end= "")

4. Use Getpass to read the password:

Import Getpassuser=getpass.getuser () passwd=getpass.getpass (' You password: ')                              print (USER,PASSWD)

Can avoid entering the password to be seen

5. Parsing command-line arguments using Argparse

Agrparse ability to parse parameters from Sys.arg and automatically generate Help information

From __future__ import print_functionimport argparsedef _argparse ():        parser = Argparse. Argumentparser (description= "This is description")        parser.add_argument ('--host ', action= ' store ',                                dest= ' Server ', default= "localhost", help= ' connect to host ')        parser.add_argument ('-t ', action= ' store_true ',                                    Default=false, dest= ' Boolean_switch ', help= ' Set a switch to True ')        return Parser.parse_args () def main ():       Parser = _argparse ()       print (parser) print (       ' host = ', Parser.server)       print (' boolean_switch= ', Parser.boolean_switch) If __name__ = = ' __main__ ':    Main ()

Format: rgumentparser.add_argument (name or flags ...) [, Action] [, Nargs] [, Const] [, Default] [, type] [, Choices] [, Required] [, help] [, Metavar] [, dest])

Name: Names of parameters

Action: Actions When a parameter is encountered

Nargs: Number of parameters

Dest: The name of the parsed argument

Type: Types of parameters

6. Use Click to create a command-line resolution

Click Compare Argparse more fast and easy

PIP Inst Click

Import Click@click.command () @click. Option ('--count ', default=1, help= ' number of greetings. ') @click. Option ('--name ', prompt= ' Your name ',              help= ' the person to greet. ') def hello (count, name): "" "Simple Program,"    greets name for a total of count times.    "" " For x in range (count):        click.echo (' Hello%s! '% name) if __name__ = = ' __main__ ':    Hello ()

Commond making a function a command-line interface

Option: Add command-line Options

Echo: Output result

Prompt: If the name parameter is not specified, enter in interactive mode

 

You can also enter the default editor like FC in Linux

Import clickmessage = Click.edit () print (message,end= "")

  

Python processing command-line arguments

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.