Python處理命令列參數

來源:互聯網
上載者:User

標籤:false   count   image   png   shell指令碼   option   return   __name__   filename   

1. 將命令列參數儲存在列表中,注意argv[0]是程式本身的名字:

import sysprint(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 sysdef 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 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

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. 使用getpass讀取密碼:

import getpassuser=getpass.getuser()passwd=getpass.getpass(‘you password: ‘)                              print(user,passwd)

可以避免輸入密碼被看見

 

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

    agrparse能夠根據從sys.arg中解析參數,並自動產生協助資訊

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

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

            name:參數的名字

    action: 遇到參數時的動作

           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 clickmessage = click.edit()print(message,end="")

  

Python處理命令列參數

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.