1. 程式人生 > >argparse.ArgumentParser以及shell中echo 命令學習

argparse.ArgumentParser以及shell中echo 命令學習

一、argparse.ArgumentParser學習

簡單例子

import argparse
parser=argparse.ArgumentParser()
parser.add_argument("echo",help="echo the string")
args=parser.parse_args()
print (args.echo)

1、匯入argparse模組

import argparse

2、建立解析器物件ArgumentParser,可以新增引數。

parser=argparse.ArgumentParser()
description:描述程式
parser=argparse.ArgumentParser(description="This is a example program ")
add_help:預設是True,可以設定False禁用

3、add_argument()方法,用來指定程式需要接受的命令引數

parser.add_argument("echo",help="echo the string")
定位引數:
parser.add_argument("echo",help="echo the string")
可選引數:
parser.add_argument("--verbosity", help="increase output verbosity")
在執行程式的時候,定位引數必選,可選引數可選。
add_argument()常用的引數:
dest:如果提供dest,例如dest="a",那麼可以通過args.a訪問該引數
default:設定引數的預設值
action:引數出發的動作
store:儲存引數,預設
store_const:儲存一個被定義為引數規格一部分的值(常量),而不是一個來自引數解析而來的值。
store_ture/store_false:儲存相應的布林值
append:將值儲存在一個列表中。
append_const:將一個定義在引數規格中的值(常量)儲存在一個列表中。
count:引數出現的次數
parser.add_argument("-v", "--verbosity", action="count", default=0, help="increase output verbosity")
version:列印程式版本資訊
type:把從命令列輸入的結果轉成設定的型別
choice:允許的引數值
parser.add_argument("-v", "--verbosity", type=int, choices=[0, 1, 2], help="increase output verbosity")
help:引數命令的介紹

4、

args=parser.parse_args()

5、呼叫

print (args.echo)

6、簡單例子

import argparse
parser = argparse.ArgumentParser(description="Boundary Sensitive Network")
parser.add_argument('start_idx', type=int)
parser.add_argument('end_idx', type=int)
args = parser.parse_args()
video_list=video_dict.keys()[args.start_idx:args.end_idx]

二、echo 命令學習

Shell 的 echo 指令與 PHP 的 echo 指令類似,都是用於字串的輸出。命令格式:

echo string

1.顯示普通字串:

echo "It is a test"

這裡的雙引號完全可以省略,以下命令與上面例項效果一致:

echo It is a test

2.顯示轉義字元

echo "\"It is a test\""

結果將是:

"It is a test"

同樣,雙引號也可以省略
3.顯示變數
read 命令從標準輸入中讀取一行,並把輸入行的每個欄位的值指定給 shell 變數

#!/bin/sh
read name 
echo "$name It is a test"

以上程式碼儲存為 test.sh,name 接收標準輸入的變數,結果將是:

[[email protected] ~]# sh test.sh
OK                     #標準輸入
OK It is a test        #輸出

4.顯示換行

echo -e "OK! \n" # -e 開啟轉義
echo "It is a test"

輸出結果:

OK!

It is a test

5.顯示不換行

#!/bin/sh
echo -e "OK! \c" # -e 開啟轉義 \c 不換行
echo "It is a test"

輸出結果:

OK! It is a test

6.顯示結果定向至檔案

echo "It is a test" > myfile

7.原樣輸出字串,不進行轉義或取變數(用單引號)

echo '$name\"'

輸出結果:

$name\"

8.顯示命令執行結果

echo `date`

注意: 這裡使用的是反引號 `, 而不是單引號 '。

結果將顯示當前日期

Thu Jul 24 10:08:46 CST 2014