Python命令行參數(shù)的項(xiàng)目實(shí)踐
Python 命令行參數(shù)為運(yùn)行程序時(shí)在命令行中接受某些信息提供了一種方便的方式。我們通常會把這些值和Python腳本的名稱一起傳遞。
要運(yùn)行 Python 程序,我們在作系統(tǒng)的命令提示符終端執(zhí)行以下命令。例如,在 Windows 中,在 Windows 命令提示符終端中輸入以下命令。
$ python script.py arg1 arg2 arg3
這里 Python 腳本名是 script.py,其他三個(gè)參數(shù)——arg1、arg2、arg3 是程序的命令行參數(shù)。
如果程序需要接受用戶輸入,則使用 Python 的 input() 函數(shù)。當(dāng)程序從命令行執(zhí)行時(shí),用戶輸入會從命令終端接收。
示例
name = input("Enter your name: ")
print ("Hello {}. How are you?".format(name))程序從命令提示符終端運(yùn)行如下 −

執(zhí)行時(shí)傳遞參數(shù)
很多時(shí)候,你可能需要把程序使用的數(shù)據(jù)放在命令行里,然后在程序內(nèi)部使用。在命令行中提供數(shù)據(jù)的一個(gè)例子是Windows或Linux中的任何DOS命令。
在Windows中,你使用以下DOS命令將文件 hello.py 重命名為 hi.py。
C:\Python311>ren hello.py hi.py
在Linux中,你可以使用mv命令 −
$ mv hello.py hi.py
這里的ren或mv是需要新舊文件名的命令。由于它們與命令對齊,因此被稱為命令行參數(shù)。
您可以從命令行向Python程序傳遞值。Python在列表對象中收集參數(shù)。Python的sys模塊通過sys.argv變量提供對任何命令行參數(shù)的訪問。sys.argv是命令行參數(shù)列表,sys.argv[0]是程序,即腳本名稱。
示例
hello.py腳本在運(yùn)行后使用input()函數(shù)接受用戶輸入。讓我們將其更改為接受來自命令行的輸入。
import sys
print ('argument list', sys.argv)
name = sys.argv[1]
print ("Hello {}. How are you?".format(name))從命令行運(yùn)行程序,如下圖所示:

輸出如下所示:
C:\Python311>python hello.py Rajan argument list ['hello.py', 'Rajan'] Hello Rajan. How are you?
命令行參數(shù)始終存儲在字符串變量中。要將它們用作數(shù)字,可以使用類型轉(zhuǎn)換函數(shù)進(jìn)行適當(dāng)?shù)霓D(zhuǎn)換。
示例
在下面的示例中,輸入了兩個(gè)數(shù)字作為命令行參數(shù)。在程序內(nèi)部,我們使用int()函數(shù)將它們解析為整數(shù)變量。
import sys
print ('argument list', sys.argv)
first = int(sys.argv[1])
second = int(sys.argv[2])
print ("sum = {}".format(first+second))它將產(chǎn)生以下輸出:
C:\Python311>python hello.py 10 20
argument list ['hello.py', '10', '20']
sum = 30
Python的標(biāo)準(zhǔn)庫包括幾個(gè)有用的模塊來解析命令行參數(shù)和選項(xiàng)——
- getopt − C風(fēng)格的命令行選項(xiàng)解析器。
- argparse − 用于命令行選項(xiàng)、參數(shù)和子命令的解析器。
Python getopt 模塊
Python提供了一個(gè)getopt模塊,可以幫助您解析命令行選項(xiàng)和參數(shù)。此模塊提供兩個(gè)函數(shù)和一個(gè)異常來啟用命令行參數(shù)解析。
getopt.getopt() 方法
此方法解析命令行選項(xiàng)和參數(shù)列表。以下是此方法的簡單語法:
getopt.getopt(args, options, [long_options])
以下是參數(shù)的詳細(xì)信息:
- args − This is the argument list to be parsed.
- options − This is the string of option letters that the script wants to recognize, with options that require an argument should be followed by a colon (:).
- long_options − This is an optional parameter and if specified, must be a list of strings with the names of the long options, which should be supported. Long options, which require an argument should be followed by an equal sign ('='). To accept only long options, options should be an empty string.
此方法返回一個(gè)由兩個(gè)元素組成的值——第一個(gè)是(選項(xiàng),值)對的列表,第二個(gè)是剝離選項(xiàng)列表后留下的程序參數(shù)列表。
返回的每個(gè)選項(xiàng)和值對都將選項(xiàng)作為其第一個(gè)元素,短選項(xiàng)以連字符作為前綴(例如“-x”),長選項(xiàng)以兩個(gè)連字符作為后綴(例如“--long option”)。
異常,getopt.GetoptError
當(dāng)在參數(shù)列表中發(fā)現(xiàn)一個(gè)無法識別的選項(xiàng),或者當(dāng)一個(gè)需要參數(shù)的選項(xiàng)沒有給出時(shí),就會出現(xiàn)這種情況。
異常的參數(shù)是一個(gè)指示錯誤原因的字符串。屬性msg和opt給出了錯誤消息和相關(guān)選項(xiàng)。
示例
假設(shè)我們想通過命令行傳遞兩個(gè)文件名,我們還想提供一個(gè)選項(xiàng)來檢查腳本的使用情況。腳本的用法如下:
usage: test.py -i <inputfile> -o <outputfile>
以下是test.py的腳本:
import sys, getopt
def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print ('Input file is "', inputfile)
print ('Output file is "', outputfile)
if __name__ == "__main__":
main(sys.argv[1:])現(xiàn)在,按如下方式運(yùn)行上述腳本:
$ test.py -h usage: test.py -i <inputfile> -o <outputfile> $ test.py -i BMP -o usage: test.py -i <inputfile> -o <outputfile> $ test.py -i inputfile -o outputfile Input file is " inputfile Output file is " outputfile
Python argparse 模塊
argparse 模塊提供了編寫非常易用命令行接口的工具。它處理如何解析 sys.argv 列表中收集的參數(shù),自動生成幫助,并在給出無效選項(xiàng)時(shí)發(fā)出錯誤信息。
設(shè)計(jì)命令行界面的第一步是設(shè)置解析器對象。這通過argparse模塊中的ArgumentParser()函數(shù)實(shí)現(xiàn)。函數(shù)可以作為描述參數(shù)給出一個(gè)解釋字符串。
首先,我們的腳本將從命令行執(zhí)行,無需任何參數(shù)。不過 使用解析器對象的parse_args()方法,但由于沒有參數(shù),因此沒有任何參數(shù)。
import argparse parser=argparse.ArgumentParser(description="sample argument parser") args=parser.parse_args()
當(dāng)上述腳本運(yùn)行時(shí) −
C:\Python311>python parser1.py C:\Python311>python parser1.py -h usage: parser1.py [-h] sample argument parser options: -h, --help show this help message and exit
第二種命令行使用方式會給出 −help 選項(xiàng),如圖所示,會生成幫助信息。−help參數(shù)默認(rèn)可用。
現(xiàn)在我們定義一個(gè)參數(shù),這個(gè)參數(shù)是腳本運(yùn)行的必定條件,如果不給出,腳本應(yīng)拋出錯誤。這里我們通過 add_argument() 方法定義參數(shù) 'user'。
import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
parser.add_argument("user")
args=parser.parse_args()
if args.user=="Admin":
print ("Hello Admin")
else:
print ("Hello Guest")該腳本的幫助現(xiàn)在顯示一個(gè)位置論元,形式為“用戶”。程序會檢查它的值是否為“管理員”,并打印相應(yīng)的消息。
C:\Python311>python parser2.py --help usage: parser2.py [-h] user sample argument parser positional arguments: user options: -h, --help show this help message and exit
使用以下命令 −
C:\Python311>python parser2.py Admin Hello Admin
但以下用法顯示的是Hello Guest message。
C:\Python311>python parser2.py Rajan Hello Guest
add_argument()方法
我們可以在 add_argument() 方法中為參數(shù)賦予默認(rèn)值。
import argparse
parser=argparse.ArgumentParser(description="sample argument parser")
parser.add_argument("user", nargs='?',default="Admin")
args=parser.parse_args()
if args.user=="Admin":
print ("Hello Admin")
else:
print ("Hello Guest")這里 nargs 是應(yīng)被消耗的命令行參數(shù)數(shù)量。'?'.如果可能,會從命令行消耗一個(gè)參數(shù),并作為一個(gè)項(xiàng)目生成。如果沒有命令行參數(shù),則會從默認(rèn)中生成值。
默認(rèn)情況下,所有參數(shù)都被視為字符串。要明確提及參數(shù)類型,請?jiān)?add_argument() 方法中使用類型參數(shù)。所有 Python 數(shù)據(jù)類型均為有效的類型值。
import argparse
parser=argparse.ArgumentParser(description="add numbers")
parser.add_argument("first", type=int)
parser.add_argument("second", type=int)
args=parser.parse_args()
x=args.first
y=args.second
z=x+y
print ('addition of {} and {} = {}'.format(x,y,z))它將產(chǎn)生以下輸出 −
C:\Python311>python parser3.py 10 20 addition of 10 and 20 = 30
在上述例子中,論證是強(qiáng)制的。為了添加可選參數(shù),可以在名稱前加上雙劃號--.以下情況下,姓氏論元是可選的,因?yàn)樗凹恿穗p劃號(--surname)。
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("name")
parser.add_argument("--surname")
args=parser.parse_args()
print ("My name is ", args.name, end=' ')
if args.surname:
print (args.surname)一個(gè)字母的參數(shù)名稱加上單段前綴,作為簡短名稱選項(xiàng)。
C:\Python311>python parser3.py Anup My name is Anup C:\Python311>python parser3.py Anup --surname Gupta My name is Anup Gupta
如果希望參數(shù)只取定義列表中的值,則定義為選擇參數(shù)。
import argparse
parser=argparse.ArgumentParser()
parser.add_argument("sub", choices=['Physics', 'Maths', 'Biology'])
args=parser.parse_args()
print ("My subject is ", args.sub)注意,如果參數(shù)值不來自列表中,則顯示無效選擇錯誤。
C:\Python311>python parser3.py Physics
My subject is Physics
C:\Python311>python parser3.py History
usage: parser3.py [-h] {Physics,Maths,Biology}
parser3.py: error: argument sub: invalid choice: 'History' (choose from
'Physics', 'Maths', 'Biology')到此這篇關(guān)于Python命令行參數(shù)的項(xiàng)目實(shí)踐的文章就介紹到這了,更多相關(guān)Python命令行參數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python/golang實(shí)現(xiàn)循環(huán)鏈表的示例代碼
這篇文章主要介紹了python/golang如何實(shí)現(xiàn)循環(huán)鏈表,幫助大家更好的理解和學(xué)習(xí)循環(huán)鏈表的實(shí)現(xiàn)方法,感興趣的朋友可以了解下2020-09-09
對python3 Serial 串口助手的接收讀取數(shù)據(jù)方法詳解
今天小編就為大家分享一篇對python3 Serial 串口助手的接收讀取數(shù)據(jù)方法詳解,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2019-06-06
Python實(shí)現(xiàn)自動化拆分Word文檔(按分節(jié)符與分頁符)的完整教程
在處理大型 Word 文檔時(shí),我們經(jīng)常需要將一個(gè)完整的文檔拆分成多個(gè)獨(dú)立的小文檔,下面我們就來看看Python如何實(shí)現(xiàn)按分頁符和分節(jié)符自動化拆分 Word 文檔吧2026-04-04
python 實(shí)現(xiàn)倒計(jì)時(shí)功能(gui界面)
這篇文章主要介紹了python 實(shí)現(xiàn)倒計(jì)時(shí)功能(gui界面),幫助大家更好的理解和使用python,感興趣的朋友可以了解下2020-11-11
python tkinter GUI繪制,以及點(diǎn)擊更新顯示圖片代碼
這篇文章主要介紹了python tkinter GUI繪制,以及點(diǎn)擊更新顯示圖片代碼,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-03-03
jupyter notebook參數(shù)化運(yùn)行python方式
這篇文章主要介紹了jupyter notebook參數(shù)化運(yùn)行python方式,具有很好的參考價(jià)值,希望對大家有所幫助。一起跟隨小編過來看看吧2020-04-04
Python實(shí)現(xiàn)批量轉(zhuǎn)換文件編碼的方法
這篇文章主要介紹了Python實(shí)現(xiàn)批量轉(zhuǎn)換文件編碼的方法,涉及Python針對文件的遍歷及編碼轉(zhuǎn)換實(shí)現(xiàn)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07

