Tsarin argparse
da ke cikin Python kayan aiki ne mai ƙarfi don sarrafawa da rarraba muhawarar layin umarni lokacin gudanar da shirin. Yana ba ku damar ayyana sigogin da ake buƙata cikin sauƙi da zaɓuɓɓuka don shirin ku kuma yana ba da hanyoyin sassauƙa don karantawa da amfani da su.
Anan ga matakan amfani da argparse
tsarin:
-
Shigo da
argparse
tsarin: Fara shirin ku ta shigo daargparse
tsarin. -
Ƙayyade
ArgumentParser
abu: ƘirƙiriArgumentParser
abu don ayyana sigogi da ake buƙata da zaɓuɓɓuka don shirin ku. -
Ƙara gardama: Yi amfani da
.add_argument()
hanyarArgumentParser
abu don ƙara mahimman sigogi da zaɓuɓɓuka don shirin ku. Kowace gardama na iya samun suna, nau'in bayanai, kwatance, da wasu halaye iri-iri. -
Fassarar gardama: Yi amfani da
.parse_args()
hanyar abuArgumentParser
don rarraba gardama daga layin umarni da adana su a cikin wani abu. -
Yi amfani da gardama: Yi amfani da ƙimar da aka adana a cikin abin da aka tantance daga mataki na baya don aiwatar da ayyuka masu dacewa da zaɓin da aka bayar daga layin umarni.
Misali: Ga misali mai sauƙi na yadda ake amfani da shi argparse
don ƙididdige jimlar lambobi biyu daga layin umarni:
import argparse
# Define the ArgumentParser object
parser = argparse.ArgumentParser(description='Calculate the sum of two numbers.')
# Add arguments to the ArgumentParser
parser.add_argument('num1', type=int, help='First number')
parser.add_argument('num2', type=int, help='Second number')
# Parse arguments from the command-line
args = parser.parse_args()
# Use the arguments to calculate the sum
sum_result = args.num1 + args.num2
print(f'The sum is: {sum_result}')
Lokacin gudanar da shirin tare da muhawara, misali: python my_program.py 10 20
, fitarwa zai zama: The sum is: 30
, kuma zai nuna jimlar lambobi biyu da aka bayar daga layin umarni.