gpt4 book ai didi

python - 我可以将 sys.argv 合并到其中吗?

转载 作者:太空狗 更新时间:2023-10-30 02:46:15 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的脚本,它将接受年龄作为参数来确定适当的入场费。 (< 6 = 免费;>= 7 且 <=14 为 10 美元;>=15 且 <=59 为 15 美元;>= 60 为 5 美元)

如果我在脚本中以 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")

最佳答案

当然,这绝对是您可以用 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 未给出或不是整数,则自动错误反馈。

关于python - 我可以将 sys.argv 合并到其中吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21410519/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com