Python命令行參數設置(args)
1.sys模塊
通過傳入sys.argv列表,這裏列表元素必須大於等於代碼中設定的長度(長了會截斷),不然會報錯。
import sys
def test_for_sys(year, name, body):
print('the year is', year)
print('the name is', name)
print('the body is', body)
if __name__ == '__main__':
try:
year, name, body = sys.argv[1:4]
test_for_sys(year, name, body)
except Exception as e:
print(sys.argv)
print(e)
2.argparse模塊
專門的參數設置模塊,功能比上面的多,使用分爲如下三步:
1.通過設置一個argparse.ArgumentParser()對象,這裏取名爲parser
2.爲parser對象添加add_argument()方法來設置參數
3.最後通過parser對象的parse_args()方法來重新獲得一個可通過屬性調用參數的對象,這裏取名爲args
import argparse
def test_for_sys(year, name, body):
print('the year is', year)
print('the name is', name)
print('the body is', body)
parser = argparse.ArgumentParser(description='Test for argparse')
parser.add_argument('--name', '-n', help='name 屬性,非必要參數')
parser.add_argument('--year', '-y', help='year 屬性,非必要參數,但是有默認值', default=2017)
parser.add_argument('--body', '-b', help='body 屬性,必要參數', required=True)
args = parser.parse_args()
if __name__ == '__main__':
try:
test_for_sys(args.year, args.name, args.body)
except Exception as e:
print(e)
add_arguments的自帶屬性有:
- name or flags:也就是在使用參數的時候使用的符號,–foo 或者 -f
- action:可以選擇參數在只提供符號而不輸入實際的值的時候給予一個默認的值
- nargs:這個屬性規定了參數可以輸入的個數
- const:這屬性跟 action 屬性一起使用
- default:這屬性就是給參數設置一個默認值
- type:這個屬性規定了參數的數據類型
- choices:這個屬性給參數限定了一個選擇的迭代,參數只能在這個範圍內選擇參數的值,否則報錯
- required:參數的值爲必填
3.click第三方庫
其使用裝飾器添加命令行屬性,之後直接調用參數名即可
import click
@click.command()
@click.option('--name','-n',default='Leijun',help='name 參數,非必須,有默認值')
@click.option('--year','-y',help='year 參數',type=int)
@click.option('--body','-b',help='body 參數 必填',required=True)
def test_for_sys(year, name, body):
print('the year is', year)
print('the name is', name)
print('the body is', body)
if __name__ == '__main__':
test_for_sys()
參考:https://tendcode.com/article/python-shell/