增加參數:parser.add_argument(argument_info):只有一個參數可以不加"-",其余的必須加“-”-->解析參數:parser" />

日韩久久久精品,亚洲精品久久久久久久久久久,亚洲欧美一区二区三区国产精品 ,一区二区福利

命令行參數_Python 筆記_20190628

系統 1895 0

1. argparse 按名稱讀取命令行參數

如何傳遞參數給Python 腳本,python 如何獲取參數值,詳見

argparse — Parser for command-line options, arguments and sub-commands

初始化: parser = argparse.ArgumentParser() --> 增加參數:
parser.add_argument(argument_info) : 只有一個參數可以不加"-",其余的必須加 “-” --> 解析參數 : parser.parse_args() --> 獲取參數: args.file…
–> 程序使用:下面2種調用程序傳參方式都可以,不需要指定順序

python ascii.py “微信截圖_20190627073701.png” -o result2.txt --width 100 --height 100 --width 100

python ascii.py --width 100 --height 100 --width 100 “微信截圖_20190627073701.png” -o result2.txt

            
              #命令行輸入參數處理
parser = argparse.ArgumentParser()

parser.add_argument('file')     #輸入文件
parser.add_argument('-o', '--output')   #輸出文件
parser.add_argument('--width', type = int, default = 80) #輸出字符畫寬
parser.add_argument('--height', type = int, default = 80) #輸出字符畫高

#獲取參數
args = parser.parse_args()
print(args.file)
print(args.output)
print(args.width)
print(args.height)

IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output

            
          

2. sys.argv 按順序讀取命令行參數

sys.argv[0] 讀取python文件本身名稱
sys.argv[1] 讀取傳入的第一個參數
sys.argv[2] 讀取傳入的第二個參數,以此類推

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string ‘-c’. If no script name was passed to the Python interpreter, argv[0] is the empty string.

https://docs.python.org/3.7/library/sys.html#module-sys

            
              
import sys

#參數驗證
if len(sys.argv) < 3:
    print("Usage: python ",sys.argv[0]," file1 file2")
    sys.exit(1) # 程序異常退出

f1 = open(sys.argv[1])  # 只讀模式打開file1
s = f1.read() # 讀取file1,將字節內容賦值給s
f1.close  # 關閉file1

f2 = open(sys.argv[2],'w') # 寫入模式打開file2
#f2.write(s)  # 將s中存儲的file1的內容 寫入f2
f2.close # 關閉 f2

            
          
            
              
import sys
print("First value", sys.argv[0])
print("All values")
for i, x  in enumerate(sys.argv):
    print(i, x)

            
          

更多文章、技術交流、商務合作、聯系博主

微信掃碼或搜索:z360901061

微信掃一掃加我為好友

QQ號聯系: 360901061

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點擊下面給點支持吧,站長非常感激您!手機微信長按不能支付解決辦法:請將微信支付二維碼保存到相冊,切換到微信,然后點擊微信右上角掃一掃功能,選擇支付二維碼完成支付。

【本文對您有幫助就好】

您的支持是博主寫作最大的動力,如果您喜歡我的文章,感覺我的文章對您有幫助,請用微信掃描上面二維碼支持博主2元、5元、10元、自定義金額等您想捐的金額吧,站長會非常 感謝您的哦!!!

發表我的評論
最新評論 總共0條評論
主站蜘蛛池模板: 从化市| 隆回县| 吐鲁番市| 哈密市| 永嘉县| 伊川县| 新余市| 通榆县| 泗洪县| 北流市| 郓城县| 铜川市| 原阳县| 新龙县| 余姚市| 安多县| 浦城县| 冕宁县| 莱阳市| 通海县| 兴隆县| 沅江市| 青铜峡市| 秀山| 山西省| 旌德县| 汝州市| 峡江县| 平南县| 利川市| 毕节市| 韩城市| 陇川县| 永城市| 郧西县| 神池县| 伊宁市| 桃源县| 历史| 江油市| 海门市|