Skip to main content
 首页 » 编程设计

python之argparse 函数参数

2025年05月04日23lvdongjie

我正在尝试使用 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