【发布时间】:2021-05-31 09:45:33
【问题描述】:
您好,任何人都可以提供帮助。我正在学习使用 argparse,例如,我想使用命令将 school.py 称为学校开始。到目前为止,我有这个,但很难处理这些论点。我这样做是对的还是我做错了什么?
if __name__ == '__main__':
parser = argparse.ArgumentParser(description="This allows quick opening of applications used within the school day")
parser.add_argument("start", help="This will open all the standard applications used within the school day.")
parser.add_argument("engine", help="This will show the Engineering folder within Documents")
parser.add_argument("bus", help="This will show the Business folder within Documents")
parser.add_argument("cs", help="This will show the Computer Science folder within Documents")
parser.add_argument("python", help="This will open the PyCharm application")
args = parser.parse_args()
try:
if len(sys.argv) > 1:
if sys.argv[1] == "engine":
engineering()
elif sys.argv[1] == "cs":
computer_science()
elif sys.argv[1] == "python":
python()
elif sys.argv[1] == "bus":
business()
elif sys.argv[1] == "start":
std_day()
except:
print("An error has occurred")
我的错误是
usage: autoSchoolDay.py [-h] start engine bus cs python
autoSchoolDay.py:错误:需要以下参数:engine、bus、cs、python
【问题讨论】:
-
当您需要添加一个可以是“start”、“engine”等的单个参数时,您正在添加多个名为“start”、“engine”等的参数,如下所示:
parser.add_argument('command', choices=['start', 'engine', 'bus', 'cs', 'python'], default='start')然后你会做if args.command == "engine":等等。 -
是的,我想称呼它为
school start或school engine -
你怎么称呼这个脚本?从操作系统外壳?使用什么命令行参数?或者你甚至知道我们所说的命令行参数是什么意思吗?
-
@JamesMcC 请试试我在评论中添加的代码,我明白你想要什么。
-
如果使用
argparse,则不需要直接解析sys.argv。但是,为您的解析器定义的逻辑与您对sys.argv的处理不同。
标签: python python-3.x argparse