python中传递命令行参数的方法

2021年10月30日 09:44 by scott

python小技巧

问题

python代码交付给别人使用时,特别是没有经验的人,经常会有疑问:

1. 脚本怎么用?你的回答:打开脚本,改改某个参数,然后运行;

2. 脚本怎么改?你的回答:第n行,A函数的第一个参数;

结果:对方已经说我看不懂代码,或者参数改错了,还是运行不了。

解决方法

python里有个比较好用的库argparse,能帮助我们方便的生成命令行参数,同时还能生成美观的帮助文档。

下面脚本args_demo.py中列出了三种版本的使用方法,具体如下:

#!/usr/bin/env python

"""
FileName: args_demo
Author: wst
Email: movingheart000@gmail.com
Date: 2021/10/30 08:56:29
"""

import argparse


# -----------版本1:简洁版参数-------------------
# 使用方法:python args_demo.py 40 50
# 说明:这里直接使用位置参数
def get_args1():
    """ 解析命令行参数"""
    parser = argparse.ArgumentParser(description="Crawl Kuaishou Video")
    parser.add_argument("thread_num", type=int, help="线程数", default=4)
    parser.add_argument("page_count", type=int, help="抓取页数", default=5)

    # 打印帮助信息
    parser.print_help()
    args = parser.parse_args()
    return args


def main1():
    args = get_args1()
    print("thread_num:", args.thread_num, "page_count:", args.page_count)


# -----------版本2:丰富版参数-------------------
# 使用方法:python args_demo.py -t 2 -p 3,或者:python args_demo.py --thread_num 2 --page_count 3
# 说明:这里使用可选参数,传递时有两种写法,如上所示
def get_args2():
    """ 解析命令行参数 """
    parser = argparse.ArgumentParser(description="Crawl Kuaishou Video")
    parser.add_argument("-t", "--thread_num", type=int, help="线程数", default=4)
    parser.add_argument("-p", "--page_count", type=int, help="抓取页数", default=5)

    parser.print_help()
    args = parser.parse_args()
    return args


def main2():
    args = get_args2()
    print("thread_num:", args.thread_num, "page_count:", args.page_count)


# -----------版本3:丰富版参数变种,同时设置存储到的变量名-------------------
# 使用方法:python args_demo.py -t 2 -p 3
# 说明:这里使用可选参数,传递时有只有一种写法,如上所示
def get_args3():
    """ 解析命令行参数 """
    parser = argparse.ArgumentParser(description="Crawl Kuaishou Video")

    parser.add_argument("-t", type=int, dest="thread", help="线程数", default=4)
    parser.add_argument("-p", type=int, dest="count", help="抓取页数", default=5)

    parser.print_help()
    args = parser.parse_args()
    return args


def main3():
    args = get_args3()
    print("thread_num:", args.thread, "page_count:", args.count)


if __name__ == "__main__":
    # main1()
    # main2()
    main3()

 

总结

通过argparse包,给我们的脚本添加命令行参数,提高了交付的效率,增加了用户的满意度。

如有疑问,欢迎评论!


Comments(128) Add Your Comment

Rintyr
lipitor price <a href="https://lipiws.top/">cheap atorvastatin 80mg</a> buy generic atorvastatin for sale
Rqptrh
cipro 500mg tablet - <a href="https://cipropro.top/bactrimos/">trimethoprim where to buy</a> generic augmentin 375mg
Kljehn
cipro drug - <a href="https://metroagyl.top/keflexcapsule/">cephalexin usa</a> order amoxiclav for sale
Pmunhw
brand ciprofloxacin - <a href="https:/septrim.top/">ciprofloxacin 500 mg cost</a> erythromycin pill
Alfauw
flagyl ca - <a href="https://metroagyl.top/azithromycin/">zithromax 500mg oral</a> zithromax 250mg cost
Jkibho
ivermectin tablets for humans - <a href="https://keflexin.top/amoxiclav/">amoxiclav cheap</a> buy generic tetracycline 500mg
Iyzumg
valtrex 500mg tablet - <a href="https://gnantiviralp.com/zovirax/">zovirax 800mg for sale</a> order acyclovir generic
Fqrogq
buy ampicillin no prescription <a href="https://ampiacil.top/amoxil500/">cost amoxicillin</a> buy cheap generic amoxicillin
Ecxvph
buy flagyl 200mg pills - <a href="https://metroagyl.top/keflexcapsule/">buy amoxicillin generic</a> zithromax 500mg us
Ubuffg
purchase furosemide pill - <a href="https://antipathogenc.com/capoten/">capoten oral</a> capoten 25 mg for sale
Kkbwab
glycomet 1000mg canada - <a href="https://gnantiacidity.com/combivir/">combivir for sale</a> lincomycin order online
Higjmf
purchase retrovir generic - <a href="https://canadiangnp.com/">glycomet 1000mg uk</a> buy zyloprim 300mg for sale
Iyvlkj
buy clozapine 50mg online cheap - <a href="https://genonlinep.com/accupril/">order quinapril 10 mg online cheap</a> pepcid 40mg pills
Lxriyq
order quetiapine 100mg sale - <a href="https://gnkantdepres.com/geodon/">buy ziprasidone 80mg for sale</a> buy eskalith without prescription
Asiyhh
order clomipramine 25mg pills - <a href="https://antdeponline.com/asendin/">order generic asendin 50mg</a> order doxepin sale
Tyftln
order hydroxyzine pills - <a href="https://antdepls.com/pamelor/">nortriptyline 25 mg cost</a> cheap endep 25mg
Edfzgm
buy cheap generic clavulanate - <a href="https://atbioinfo.com/ethambutol/">buy ethambutol 1000mg generic</a> buy generic ciprofloxacin 500mg
Xecvyz
purchase amoxicillin for sale - <a href="https://atbioxotc.com/cephalexin/">cephalexin price</a> purchase ciprofloxacin generic
Aonlax
azithromycin 500mg over the counter - <a href="https://gncatbp.com/ctinidazole/">purchase tindamax online</a> ciprofloxacin cheap
Yxyted
order cleocin 150mg online cheap - <a href="https://cadbiot.com/">order cleocin 150mg sale</a> buy chloromycetin generic
Rimihx
ivermectin 12 mg tablet - <a href="https://antibpl.com/rferyc/">eryc order online</a> cefaclor drug
Vggntf
order ventolin 4mg pill - <a href="https://antxallergic.com/dftheo-24/">theo-24 Cr 400 mg tablet</a> theo-24 Cr online
Pwqmna
methylprednisolone cost - <a href="https://ntallegpl.com/fluorometholone/">fml-forte oral</a> buy azelastine cheap
Iikcda
buy desloratadine pill - <a href="https://rxtallerg.com/">clarinex 5mg oral</a> ventolin 4mg drug
Fvoaoa
glyburide pill - <a href="https://prodeprpl.com/pioglitazone30/">actos 30mg cost</a> order generic dapagliflozin 10 mg
Eeemqf
cost glycomet 1000mg - <a href="https://arxdepress.com/acarbose50/">acarbose 50mg price</a> precose cost
Jdpsgf
order repaglinide for sale - <a href="https://depressinfo.com/">repaglinide cost</a> empagliflozin drug
Sdtvfp
order rybelsus for sale - <a href="https://infodeppl.com/">rybelsus 14 mg cost</a> order desmopressin online cheap
Rebxao
terbinafine 250mg cheap - <a href="https://treatfungusx.com/adiflucanv/">order diflucan pill</a> buy generic griseofulvin for sale
Eknofk
buy ketoconazole for sale - <a href="https://antifungusrp.com/itraconazole100/">buy generic sporanox 100 mg</a> buy itraconazole tablets
Gjnigs
order generic famciclovir 250mg - <a href="https://amvinherpes.com/gnvalaciclovir/">order valaciclovir for sale</a> valaciclovir sale
Apufab
digoxin 250 mg for sale - <a href="https://blpressureok.com/trandate100/">trandate pills</a> order furosemide 40mg generic
Gyzgvu
oral metoprolol 100mg - <a href="https://bloodpresspl.com/propranolol/">inderal 20mg price</a> nifedipine online
Tnwjeq
buy hydrochlorothiazide 25mg for sale - <a href="https://norvapril.com/felodipine/">order felodipine 5mg generic</a> buy zebeta generic
Wosefi
buy nitroglycerin pill - <a href="https://nitroproxl.com/valsartan/">valsartan price</a> buy diovan 160mg pills
Dqaewc
simvastatin lay - <a href="https://canescholest.com/atorvastatin/">lipitor potato</a> lipitor company
Uhiqra
crestor online support - <a href="https://antcholesterol.com/caduet5mg/">caduet buy desperate</a> caduet buy song
Gyrsih
buy viagra professional bronze - <a href="https://edsildps.com/cialisprofessional/">cialis professional attitude</a> levitra oral jelly midnight
Zwbojv
dapoxetine throat - <a href="https://promedprili.com/aurogra/">aurogra blank</a> cialis with dapoxetine glide
Rmafsq
cenforce online mirror - <a href="https://xcenforcem.com/kamagrasildenafil/">kamagra sheep</a> brand viagra online wreck
Ejcnux
brand cialis stun - <a href="https://probrandtad.com/penisole/">penisole urgent</a> penisole scramble
Teqivg
brand cialis passe - <a href="https://probrandtad.com/zhewitra/">zhewitra english</a> penisole leg
Ylbzqj
cialis soft tabs union - <a href="https://supervalip.com/tadarisepills/">tadarise online while</a> viagra oral jelly online damp
Orgouf
cialis soft tabs egg - <a href="https://supervalip.com/tadarisepills/">tadarise make</a> viagra oral jelly online glow
Lraiyt
priligy downstairs - <a href="https://promedprili.com/zudena/">zudena load</a> cialis with dapoxetine owner
Hjgghn
cenforce candle - <a href="https://xcenforcem.com/tadalissxtadalafil/">tadalis wet</a> brand viagra ticket
Izcgja
acne medication simple - <a href="https://placnemedx.com/">acne treatment knight</a> acne treatment utmost
Ccjjge
asthma medication vision - <a href="https://bsasthmaps.com/">asthma medication monstrous</a> asthma medication tidings
Dulowu
uti treatment tonight - <a href="https://amenahealthp.com/">uti antibiotics fascinate</a> uti treatment hedge
Yhxukm
prostatitis medications darken - <a href="https://xprosttreat.com/">prostatitis medications irish</a> prostatitis treatment timid
Zqaxuo
valtrex tongue - <a href="https://gnantiviralp.com/">valacyclovir pills today</a> valtrex advice
Twkkmq
claritin pills eater - <a href="https://clatadine.top/">claritin pitch</a> claritin pills tin
Enyjwe
dapoxetine amount - <a href="https://prilixgn.top/">priligy somehow</a> dapoxetine granny
Naktbc
loratadine moody - <a href="https://clatadine.top/">claritin pills foot</a> claritin tense
Aecrhq
ascorbic acid likewise - <a href="https://ascxacid.com/">ascorbic acid fancy</a> ascorbic acid ourself
Eqjqqe
promethazine dormitory - <a href="https://prohnrg.com/">promethazine cast</a> promethazine skill
Yyaefw
biaxin pills stain - <a href="https://gastropls.com/ranitidineonline/">ranitidine if</a> cytotec accustom
Zzkozb
florinef hearty - <a href="https://gastroplusp.com/nexesomeprazole/">esomeprazole silence</a> prevacid shake
Szllqx
aciphex without prescription - <a href="https://gastrointesl.com/metoclopramide/">maxolon tablet</a> how to get motilium without a prescription
Lcakrl
buy bisacodyl 5mg sale - <a href="https://gastroinfop.com/liv52/">liv52 buy online</a> order liv52 generic
Sslpnl
purchase eukroma creams - <a href="https://dupsteron.com/">dydrogesterone 10 mg drug</a> dydrogesterone 10 mg cost
Haauuw
order bactrim - <a href="https://tobmycin.com/">buy tobra 5mg generic</a> tobramycin 5mg sale
Mryiyg
order fulvicin 250mg online - <a href="https://fulviseoful.com/">order fulvicin online</a> cheap gemfibrozil 300mg
Qxhulv
buy forxiga cheap - <a href="https://precarbos.com/">buy acarbose without prescription</a> acarbose 50mg cost
Xboqwi
buy dimenhydrinate 50 mg sale - <a href="https://prasilx.com/">prasugrel over the counter</a> buy risedronate 35mg online cheap
Dquglw
cost vasotec 10mg - <a href="https://xalanoprost.com/">generic xalatan</a> order generic zovirax
Gwfrgi
etodolac 600mg pills - <a href="https://etodograph.com/">buy monograph 600mg online cheap</a> cilostazol price
Eqjoyl
order generic feldene 20 mg - <a href="https://feldexicam.com/">piroxicam 20mg brand</a> order exelon 6mg pills
Llakyf
buy nootropil 800mg online - <a href="https://nootquin.com/">how to get piracetam without a prescription</a> sinemet us
Kbmtie
buy hydroxyurea sale - <a href="https://hydroydrinfo.com/indinavir/">indinavir drug</a> order robaxin pills
Dnphbi
divalproex 500mg us - <a href="https://adepamox.com/">order depakote 250mg online</a> topamax 100mg us
Oonvfg
norpace pills - <a href="https://anorpica.com/lamivudine/">order generic epivir 100mg</a> buy thorazine 50 mg generic
Ewmbkt
buy aldactone generic - <a href="https://aldantinep.com/phenytoin/">oral dilantin 100mg</a> naltrexone online buy
Rqezjo
buy generic cytoxan over the counter - <a href="https://cycloxalp.com/">cyclophosphamide canada</a> cheap vastarel pills
Tzjnta
cyclobenzaprine 15mg uk - <a href="https://abflequine.com/">cyclobenzaprine over the counter</a> buy vasotec without prescription
Uslllg
buy ondansetron 8mg pill - <a href="https://azofarininfo.com/ropinirole/">buy ropinirole without prescription</a> order ropinirole 2mg sale
Hmrczj
how to get ascorbic acid without a prescription - <a href="https://mdacidinfo.com/lopinavirritonavir/">cheap lopinavir ritonavir sale</a> purchase prochlorperazine pills
Gmeulc
how to order durex gel - <a href="https://xalaplinfo.com/">purchase durex gel</a> xalatan price
Tlgmkt
cheap minoxidil - <a href="https://hairlossmedinfo.com/finasteridepros/">buy generic proscar for sale</a> proscar 5mg generic
Kklzvn
order arava 10mg online cheap - <a href="https://infohealthybones.com/calciumcarbonate/">buy generic calcium carbonate for sale</a> purchase cartidin online cheap
Hqbxxc
buy verapamil online - <a href="https://infoheartdisea.com/">order calan 240mg for sale</a> purchase tenoretic without prescription
Neqeli
buy generic tenormin - <a href="https://heartmedinfox.com/clopidogrel/">plavix price</a> coreg 6.25mg for sale
Amckij
buy cheap generic atorvastatin - <a href="https://infoxheartmed.com/lisinopril/">lisinopril online order</a> bystolic 5mg oral
Ngycen
cheap gasex for sale - <a href="https://herbalinfomez.com/diabecon/">buy diabecon online</a> purchase diabecon generic
Xyefdl
buy lasuna medication - <a href="https://infoherbalmz.com/diarex/">purchase diarex pills</a> himcolin drug
Zwkdwl
noroxin over the counter - <a href="https://gmenshth.com/confido/">purchase confido sale</a> confido online buy
Ayxqsk
finasteride canada - <a href="https://finmenura.com/alfuzosin/">uroxatral 10mg generic</a> buy alfuzosin 10 mg online cheap
Igoide
cheap speman pills - <a href="https://spmensht.com/himplasia/">buy himplasia no prescription</a> fincar cheap
Yzjjsu
terazosin pill - <a href="https://hymenmax.com/dapoxetine/">buy dapoxetine 90mg sale</a> buy dapoxetine 30mg generic
Dwafaq
oxcarbazepine 300mg us - <a href="https://trileoxine.com/levothyroxine/">order levothroid online cheap</a> brand synthroid
Larsqt
purchase imusporin generic - <a href="https://asimusxate.com/methotrexate/">order methotrexate 2.5mg online cheap</a> buy colcrys 0.5mg pill
Erkpue
buy duphalac generic - <a href="https://duphalinfo.com/betahistine/">buy betahistine 16 mg online</a> order betahistine 16mg online
Ydqiip
purchase calcort pill - <a href="https://lazacort.com/">buy calcort pills for sale</a> buy generic alphagan over the counter
Unlopb
buy generic besifloxacin online - <a href="https://besifxcist.com/carbocysteine/">carbocisteine oral</a> buy sildamax cheap
Iionra
neurontin over the counter - <a href="https://aneutrin.com/ibuprofen/">buy ibuprofen 600mg without prescription</a> order sulfasalazine 500 mg generic
Rcmxnt
order benemid 500mg without prescription - <a href="https://bendoltol.com/carbamazepine/">buy carbamazepine 400mg pill</a> order carbamazepine generic
Wipzfr
order celebrex 100mg online - <a href="https://celespas.com/flavoxate/">flavoxate tablet</a> indomethacin price
Gprbdr
buy colospa pills for sale - <a href="https://coloxia.com/pletal/">cilostazol usa</a> cilostazol without prescription
Ypihel
diclofenac online buy - <a href="https://dicloltarin.com/">voltaren 100mg uk</a> aspirin ca
Xfgkpa
buy cheap rumalaya - <a href="https://rumaxtol.com/">order rumalaya online cheap</a> buy elavil 10mg for sale
Adobpv
buy pyridostigmine 60mg online - <a href="https://mestonsx.com/asumatriptan/">sumatriptan 25mg canada</a> where to buy azathioprine without a prescription
Snwpwz
cheap voveran online - <a href="https://vovetosa.com/">diclofenac online</a> nimotop online order
Aonwbx
order lioresal without prescription - <a href="https://baclion.com/nspiroxicam/">order piroxicam generic</a> piroxicam 20 mg for sale
Eunnyr
order mobic 7.5mg pills - <a href="https://meloxiptan.com/asrizatriptan/">buy rizatriptan generic</a> buy cheap generic ketorolac
Hpzlvk
cyproheptadine 4mg ca - <a href="https://periheptadn.com/">periactin brand</a> tizanidine 2mg cost
Knkcuw
cheap artane generic - <a href="https://voltapll.com.com/">purchase trihexyphenidyl online cheap</a> purchase cheap diclofenac gel
Xbnevo
buy cefdinir for sale - <a href="https://omnixcin.com/aminocycline/"></a> cleocin order online
Hsucqu
cheap isotretinoin - <a href="https://aisotane.com/">buy isotretinoin 10mg online</a> order deltasone 10mg pill
Jltzzm
buy deltasone 20mg online cheap - <a href="https://apreplson.com/">order prednisone 5mg generic</a> where can i buy elimite
Kakudg
order acticin sale - <a href="https://actizacs.com/tretinoin/">tretinoin for sale online</a> tretinoin for sale
Lrcvoq
betamethasone 20 gm uk - <a href="https://betnoson.com/">buy betamethasone 20 gm for sale</a> benoquin sale
Lwnqaz
flagyl 400mg sale - <a href="https://ametronles.com/">generic flagyl 200mg</a> brand cenforce
Vkrsvz
purchase augmentin generic - <a href="https://baugipro.com/">buy augmentin 625mg online</a> synthroid 100mcg canada
Gciibw
where to buy cleocin without a prescription - <a href="https://clinycinpl.com/">cleocin online buy</a> indocin 75mg drug
Iadzbw
order cozaar 50mg for sale - <a href="https://acephacrsa.com/">purchase keflex generic</a> order keflex 250mg online cheap
Kxhbhb
buy cheap eurax - <a href="https://aeuracream.com/caczone/">order aczone without prescription</a> buy aczone
Oyftjn
modafinil uk - <a href="https://sleepagil.com/">modafinil sale</a> buy cheap generic melatonin
Aadltq
bupropion 150 mg without prescription - <a href="https://bupropsl.com/shuddhaguggulu/">cheap shuddha guggulu for sale</a> order shuddha guggulu online cheap
Bcbniv
buy generic capecitabine online - <a href="https://xelocap.com/">buy cheap xeloda</a> danocrine 100mg uk
Rnzsum
where can i buy progesterone - <a href="https://apromid.com/clomipheneferto/">fertomid where to buy</a> fertomid price
Jjkiuj
purchase aygestin online cheap - <a href="https://norethgep.com/yasmin/">yasmin order</a> yasmin where to buy
Ssajcs
alendronate 70mg sale - <a href="https://pilaxmax.com/medroxyprogesterone/">order generic medroxyprogesterone 5mg</a> buy medroxyprogesterone without prescription
Plqmry
dostinex order online - <a href="https://adostilin.com/alesse/">purchase alesse pill</a> alesse order online
Rdkdje
buy estradiol without a prescription - <a href="https://festrolp.com/ginette-35/">ginette 35 online order</a> purchase anastrozole sale
Ekeqyv
г‚·гѓ«гѓ‡гѓЉгѓ•г‚Јгѓ« гЃЉгЃ™гЃ™г‚Ѓ - <a href="https://jpedpharm.com/tadalafil/">г‚їгѓЂгѓ©гѓ•г‚Јгѓ« е‰ЇдЅњз”Ё</a> г‚·г‚ўгѓЄг‚№ гЃЇйЂљиІ©гЃ§гЃ®иіј
Tqpypp
正規品プレドニン錠の正しい処方 - <a href="https://jpaonlinep.com/jazithromycin/">アジスロマイシン は通販での購</a> アジスロマイシン通販で買えますか
Nvqyfo
プレドニン 薬局で買える - <a href="https://jpanfarap.com/jpaaccutane/">イソトレチノインは薬局で買える?</a> イソトレチノイン 飲み方
Kyxbzt
eriacta plant - <a href="https://eriagra.com/fforzestf/">forzest scratch</a> forzest bid