1. argparse 按名稱(chēng)讀取命令行參數(shù)
如何傳遞參數(shù)給Python 腳本,python 如何獲取參數(shù)值,詳見(jiàn)
argparse — Parser for command-line options, arguments and sub-commands
初始化: parser = argparse.ArgumentParser() --> 增加參數(shù):
parser.add_argument(argument_info) : 只有一個(gè)參數(shù)可以不加"-",其余的必須加 “-” --> 解析參數(shù) : parser.parse_args() --> 獲取參數(shù): args.file…
–> 程序使用:下面2種調(diào)用程序傳參方式都可以,不需要指定順序
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
#命令行輸入?yún)?shù)處理
parser = argparse.ArgumentParser()
parser.add_argument('file') #輸入文件
parser.add_argument('-o', '--output') #輸出文件
parser.add_argument('--width', type = int, default = 80) #輸出字符畫(huà)寬
parser.add_argument('--height', type = int, default = 80) #輸出字符畫(huà)高
#獲取參數(shù)
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 按順序讀取命令行參數(shù)
sys.argv[0] 讀取python文件本身名稱(chēng)
sys.argv[1] 讀取傳入的第一個(gè)參數(shù)
sys.argv[2] 讀取傳入的第二個(gè)參數(shù),以此類(lèi)推
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
#參數(shù)驗(yàn)證
if len(sys.argv) < 3:
print("Usage: python ",sys.argv[0]," file1 file2")
sys.exit(1) # 程序異常退出
f1 = open(sys.argv[1]) # 只讀模式打開(kāi)file1
s = f1.read() # 讀取file1,將字節(jié)內(nèi)容賦值給s
f1.close # 關(guān)閉file1
f2 = open(sys.argv[2],'w') # 寫(xiě)入模式打開(kāi)file2
#f2.write(s) # 將s中存儲(chǔ)的file1的內(nèi)容 寫(xiě)入f2
f2.close # 關(guān)閉 f2
import sys
print("First value", sys.argv[0])
print("All values")
for i, x in enumerate(sys.argv):
print(i, x)
更多文章、技術(shù)交流、商務(wù)合作、聯(lián)系博主
微信掃碼或搜索:z360901061

微信掃一掃加我為好友
QQ號(hào)聯(lián)系: 360901061
您的支持是博主寫(xiě)作最大的動(dòng)力,如果您喜歡我的文章,感覺(jué)我的文章對(duì)您有幫助,請(qǐng)用微信掃描下面二維碼支持博主2元、5元、10元、20元等您想捐的金額吧,狠狠點(diǎn)擊下面給點(diǎn)支持吧,站長(zhǎng)非常感激您!手機(jī)微信長(zhǎng)按不能支付解決辦法:請(qǐng)將微信支付二維碼保存到相冊(cè),切換到微信,然后點(diǎn)擊微信右上角掃一掃功能,選擇支付二維碼完成支付。
【本文對(duì)您有幫助就好】元
