python - argparse 函数参数

标签 python python-3.x argparse

我正在尝试使用 argparse 创建带有参数的脚本,但我无法做到。

我的脚本的名称是pipeline,它有一些选项参数,例如 -b、-c、-i 和 -r。

如果您调用脚本 ./pipeline -b 应该会给出一个错误,要求提供 git 存储库路径,但我无法执行此操作。

from git import Repo
import os
import sys
import subprocess
import argparse

class Ci:

    def build(self,args):
        cloned_repo = Repo.clone_from(args)
        print("clonning repository " + args)
        cloned_repo

        dir = git.split('/')(-1)

        if os.path.isdir(dir):
            print("repository cloned successfully")
        else:
            print("error to clone repository")


if __name__ == '__main__':

    parser = argparse.ArgumentParser()

    parser.add_argument('-b','-build',action='store_true', help='execute mvn clean install')
    parser.add_argument('-c','-compress',action='store_true',help='zip a directory recursively')
    parser.add_argument('-i','-integration',action='store_true',help='execute mvn verify')
    parser.add_argument('-r','-release',action='store_true',help='execute build,integration and compress respectively')
    args = parser.parse_args()

    if args.b:
        a = Ci()
        a.build()

    if len(sys.argv) < 2:
        parser.print_help()
        sys.exit(1)

我无法使该子参数起作用,并且找不到将此参数传递给我的 build 函数的方法。

例如:

./pipeline -b

Output: error missins git path
./pipeline -b https://git/repo
Output: clonning repo

并且字符串“https://git/repo”必须作为参数传递给我的build函数:

我怎样才能让它发挥作用?

最佳答案

首先注意一下约定:通常较长的选项名称前面有两个连字符,例如 '--build'

第二,'store_true' 是您使用 '-b' 执行的操作,这意味着 argparse 不需要后面有参数,它只是设置 args.build 变量设置为 True(如果参数不存在,则会将其设置为 False)

尝试删除 action='store_true',然后它将默认将在参数列表中找到的下一个值存储到 args.build

关于python - argparse 函数参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49408644/

相关文章:

python - pandas- fetch_pandas_all 连接器杀死内核

python - DJANGO - 文件未找到错误 : [Errno 2] No such file or directory: '' when trying to acess a file

python - 是否可以添加带有列表理解的 where 子句?

python - Argparse - 如何指定默认子命令

python - 如何使 argparse 仅适用于一个参数,即使传递了许多参数?

python - 传输异常

python xgboost : kernel died

python - Series.sort() 和 Series.order() 有什么区别?

python-3.x - 成功检索结果后,Sqlalchemy Snowflake 未关闭连接

python - 使用 python argparse 递归