【问题标题】:Automation of tasks with argparse Python3使用 argparse Python3 自动化任务
【发布时间】: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 startschool engine
  • 你怎么称呼这个脚本?从操作系统外壳?使用什么命令行参数?或者你甚至知道我们所说的命令行参数是什么意思吗?
  • @JamesMcC 请试试我在评论中添加的代码,我明白你想要什么。
  • 如果使用argparse,则不需要直接解析sys.argv。但是,为您的解析器定义的逻辑与您对sys.argv 的处理不同。

标签: python python-3.x argparse


【解决方案1】:
parser = argparse.ArgumentParser(description="This allows quick opening of applications used within the school day")

parser.add_argument('command', choices=['start', 'engine', 'bus', 'cs', 'python'])

args = parser.parse_args()

try:
    if args.command:
        if args.command == "engine":
            engineering()
        elif args.command == "cs":
            computer_science()
        elif args.command == "python":
            python()
        elif args.command == "bus":
            business()
        elif args.command == "start":
            std_day()
except Exception as e:
    print("An error has occurred", e)

【讨论】:

  • 这行得通,现在我明白了。问题虽然。如果所有命令都合并为一个,我现在如何制作帮助部分
  • 你不是第一个想做你想做的事的人。您可以在互联网上的堆栈溢出或教程中找到其他人询问此问题,关键字是“子命令”。我还将您链接到文档,了解您应该在评论中尝试使用的内容。
猜你喜欢
  • 2017-08-23
  • 1970-01-01
  • 2011-06-20
  • 2020-10-19
  • 1970-01-01
  • 1970-01-01
  • 2020-01-05
  • 2014-09-17
  • 2020-03-21
相关资源
最近更新 更多