Python處理命令行參數


1. 將命令行參數保存在列表中,注意argv[0]是程序本身的名字:
import sys
print(sys.argv)                                                       
print(sys.argv[1])

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

2. 使用sys.stdin和fileinput讀取標准輸入,並打印在終端類似shell中的管道

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

 可以像shell腳本一樣,通過標准輸入給程序輸入內容

       python read_stdin.py  </etc/passwd

       python read_stdin.py -

       cat /etc/passwd |python read_stdin.py 

將標准輸入保存在一個列表中

import sys
def get_content():                                                    
     return sys.stdin.readlines() 
print(get_content())

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

 3. 利用fileinput讀取標准輸入

#/usr/bin/env python
#coding=utf-8                                                         
import fileinput
for 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

fileinput常用於從文件中讀取內容

import fileinput

for line in fileinput.input():
    meta = [fileinput.filename(), fileinput.fileno(), fileinput.filelineno(),
            fileinput.isfirstline(), fileinput.isstdin()]
    print(*meta, end="")
    print()
    print(line, end="") 

  

4. 使用getpass讀取密碼:

import getpass

user=getpass.getuser()
passwd=getpass.getpass('you password: ')                              
print(user,passwd)

可以避免輸入密碼被看見

 

5.使用argparse解析命令行參數

    agrparse能夠根據從sys.arg中解析參數,並自動生成幫助信息

from __future__ import print_function
import argparse

def _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()

  格式:rgumentParser.add_argument(name or flags...[, action][, nargs][, const][, default][, type][, choices][, required][, help][, metavar][, dest])

            name:參數的名字

     action: 遇到參數時的動作,默認為store,store_xx,表示將參數轉換為xx

           nargs:參數的個數

           dest:解析后的參數的名字

           type:參數的類型

 

 6. 使用Click創建命令行解析

   Click比較argparse更加的快速和簡單

   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 that greets NAME for a total of COUNT times."""
    for x in range(count):
        click.echo('Hello %s!' % name)

if __name__ == '__main__':
    hello()

 commond讓函數成為命令行接口

   option:增加命令行選項

   echo:輸出結果

   prompt:如果沒有指定name這個參數時,會進入交互模式下輸入

 

也可以像Linux中的fc一樣進入默認編輯器

import click
message = click.edit()
print(message,end="")

 

7. 使用prompt_toolkit打造交互式命令行工具

pip install prompt_toolkit

from prompt_toolkit import prompt

while True:
    user_input = prompt('>')
    print(user_input)

  Linux下的快捷鍵都可以使用,輸入時退格鍵,也不會出現亂碼

加入歷史輸入功能

from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory

while True:
    user_input = prompt('>',
         history=FileHistory('history.txt'),
       )
    print(user_input)

  加入自動提示功能

from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory

while True:
    user_input = prompt('>',
                        history=FileHistory('history.txt'),
                        auto_suggest=AutoSuggestFromHistory(),
                       )
    print(user_input)

  會以按字體進行提示

加入自動補全功能:

from __future__ import unicode_literals
from prompt_toolkit import prompt
from prompt_toolkit.history import FileHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
from prompt_toolkit.contrib.completers import WordCompleter

SQLCompleter = WordCompleter(['select', 'from', 'insert', 'update', 'delete', 'drop'],
                             ignore_case=True)

while True:
    user_input = prompt('SQL>',
                        history=FileHistory('history.txt'),
                        auto_suggest=AutoSuggestFromHistory(),
                        completer=SQLCompleter,
                        )
    print(user_input)

  按tab鍵就可以自動補全

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM