我正在尝试创建一个简单的脚本,它将接受年龄作为参数来确定适当的入学费用。 (< 6 =免费;> = 7且< = 14是10美元;> = 15< = 59是15美元;> = 60是5美元)
如果我在脚本中输入age = __的年龄,我设法让脚本工作,但我希望能够在Run脚本的Arguments框中传入age作为参数窗口。我想我应该可以使用sys.argv,但我还没有弄清楚如何。我怀疑它与sys.argv想要的东西和我提供的东西之间存在某种分歧有关 - 可能与字符串和整数不匹配?
有什么想法吗?
# Enter age
age = 5
if age < 7:
print ("Free Admission")
elif age < 15:
print ("Admission: $10")
elif age < 60:
print ("Admission: $15")
else:
print ("Admission: $5")
答案 0 :(得分:4)
当然,这绝对是你可以用sys.argv
做的事情;只需考虑sys.argv[0]
是脚本名称,其中的所有值都是字符串:
import sys
if len(sys.argv) > 1:
try:
age = int(sys.argv[1])
except ValueError:
print('Please give an age as an integer')
sys.exit(1)
else:
print('Please give an age as a command line argument')
sys.exit(1)
Python附带argparse
module,这使得解析sys.argv
参数更加容易:
import argparse
parser = argparse.ArgumentParser('Admission fee determination')
parser.add_argument('age', type=int, help='the age of the visitor')
args = parser.parse_args()
age = args.age
其中age
已经是整数。作为额外的奖励,您的脚本也会得到一个帮助文本:
$ python yourscript.py -h
usage: Admission fee determination [-h] age
positional arguments:
age the age of the visitor
optional arguments:
-h, --help show this help message and exit
如果未给出age
或不是整数,则和自动错误反馈。
答案 1 :(得分:1)
# here you import `sys` that enables access to `sys.argv`
import sys
# then you define a function that will embed your algorithm
def admission_fee(age):
age = int(age)
if age < 7:
print ("Free Admission")
elif age < 15:
print ("Admission: $10")
elif age < 60:
print ("Admission: $15")
else:
print ("Admission: $5")
# if you call this python module from the command line, you're in `__main__` context
# so if you want to reuse your module from another code, you can import it!
if __name__ == "__main__":
# here you use the first argument you give to your code,
# sys.argv[0] being the name of the python module
admission_fee(sys.argv[1])
正如Martijn所说,您可以使用argparse
模块,或者我现在更喜欢使用docopt
模块,这样可以更轻松,更好地实施!
作为docopt使用的一个例子:
"""Usage: calcul_fee.py [-h] AGE
Gets the admission fee given the AGE
Arguments:
AGE age of the person
Options:
-h --help"""
from docopt import docopt
def admission_fee(age):
age = int(age)
if age < 7:
print ("Free Admission")
elif age < 15:
print ("Admission: $10")
elif age < 60:
print ("Admission: $15")
else:
print ("Admission: $5")
if __name__ == '__main__':
arguments = docopt(__doc__)
admission_fee(arguments.AGE)