估计有很多小伙伴在linux系统上或win的doc中遇到没有UI页面的程序,只能通过命令行输入参数的形式去运行

那么python是怎么实现的呢?

熟悉python的小伙伴都知道python有个原生库 sys,顾名思义都是关于系统上的一些功能

sys的方法非常多,本篇文章不做过多个拓展,只讲其中一个方法。

sys.argv 该方法用于接受运行文件时附带的其他命令行信息,以空格作为分隔,return出list格式的字符串

D:\code\apiautotest>python run.py a s d e

['run.py', 'a', 's', 'd', 'e']

例子中在运行run.py时 在后面接了任意参数,最终打印了 运行文件和其他参数

到这里我们完成了命令行传参的关键一步,接受命令行的参数

这个时候我们凭借以上的信息通过对list的遍历也能获得相关的参数,但这样的话逻辑需要写的很多。

有没有一个库可以给我们直接分辨出哪些是我们要的参数呢?

这就是我们本篇文章要介绍的另一个库 getopt。这个库也是原生库 无需安装

这个库里面的方法非常简单,看似源码有几个函数,其实都是围绕主方法使用的

我们只要懂 getopt.getopt(args, shortopts, longopts = [])即可

以下是这个方法的源码,doc中说的很清楚

def getopt(args, shortopts, longopts = []):

"""getopt(args, options[, long_options]) -> opts, args

Parses command line options and parameter list. args is the

argument list to be parsed, without the leading reference to the

running program. Typically, this means "sys.argv[1:]". shortopts

is the string of option letters that the script wants to

recognize, with options that require an argument followed by a

colon (i.e., the same format that Unix getopt() uses). If

specified, longopts is a list of strings with the names of the

long options which should be supported. The leading '--'

characters should not be included in the option name. Options

which require an argument should be followed by an equal sign

('=').

The return value consists of two elements: the first is a list of

(option, value) pairs; the second is the list of program arguments

left after the option list was stripped (this is a trailing slice

of the first argument). Each option-and-value pair returned has

the option as its first element, prefixed with a hyphen (e.g.,

'-x'), and the option argument as its second element, or an empty

string if the option has no argument. The options occur in the

list in the same order in which they were found, thus allowing

multiple occurrences. Long and short options may be mixed.

"""

opts = []

if type(longopts) == type(""):

longopts = [longopts]

else:

longopts = list(longopts)

while args and args[0].startswith('-') and args[0] != '-':

if args[0] == '--':

args = args[1:]

break

if args[0].startswith('--'):

opts, args = do_longs(opts, args[0][2:], longopts, args[1:])

else:

opts, args = do_shorts(opts, args[0][1:], shortopts, args[1:])

return opts, args

参数args:用来接受输入参数即将 sys.argv中去掉首个运行文件的列表传进去 == sys.argv[1:]

参数shortopts:短选项(单个字母)后面带冒号(:)时 使用该参数时必须附带参数,否则报错,使用时要在短选项前加 - (-a)此处为字符串

参数longopts:长选项(单词)后面带等号(=)时 使用该参数时必须附带参数,否则报错,使用时要在长选项前加 -- (--argv);此处时列表

return两个参数

opts :包含元组的列表,此处只有函数设置好的选项名字及所带的参 [(opt1, value1), (opt2, value2)]

args : 包含字符串的列表,此处为未在函数中设置好的选项,跟sys.argv一样以空格分隔

option, args = getopt.getopt(args, "e:p:d:h", ["help", "env=", "product=", "report_path="])

# 短选项有:e、p、d、h 其中使用e、p、d后面必须带有参数

# 长选项有:help、env、product、report_path 其中使用env、product、report_path后面必须带有参数

tips:报错时,报错类型为:getopt.GetoptError,只有要求带参选项没有带参才会报,如果压根就没有输入该选项是不会报错的(此时注意逻辑判断)

以下实例场景为多环境多产品线结合jenkins实现CI/CD以及allure报告输出

建议结合jenkins&allure&pytest 参数化构建一起观看效果更佳

下方实例有一个bug:如果运行文件时不传 env 及 product 这两个参数 整个程序都无法执行

不过实际情况无影响所以未做相关措施

-e --env 环境 必须带参

-p --product 产品线 必须带参

-d --report_path allure报告路径(基于工程目录) 必须带参

-h --help 帮助 无需带参

import sys

import getopt

import pytest

from common.constant import REPORT_DIR

from common.context import Context

def main(args):

path = REPORT_DIR + "/allure" # 默认报告存放地址

try: # 异常捕获,如果有选项未带参时给予使用提示

option, args = getopt.getopt(args, "e:p:d:h", ["help", "env=", "product=", "report_path"])

except getopt.GetoptError:

print("run.py \n-h -e -p -d \n")

sys.exit()

for key, value in option: # 遍历opt及value

if key in ("-h", "--help"):

print("run.py \n-h -e -p -d ")

break

elif key in ("-e", "--env"):

setattr(Context, "env", value) # 此处跟本文无关

elif key in ("-p", "--product"):

setattr(Context, "product", value) # 此处跟本文无关

elif key in ("-d", "--report_path"):

path = value

else:

raise TypeError("args error")

pytest.main(["-v", "-m", "smoke", "--alluredir={}".format(path)])

if __name__ == '__main__':

argv = sys.argv[1:]

main(argv)

python3输入参数_python3 十一、命令行传参相关推荐

  1. Java学习第八天<什么是方法><方法的定义和调用><方法的重载><命令行传参><可变参数><递归详解>

    什么是方法 System.out.println(); 调用系统类里的标准输出对象(out)中的方法println public class Demo01 {//main 方法public stati ...

  2. matlab读取txt数据绘图(python命令行传参)

    (1)命令行实现高斯分布 一:综述 Python唯一支持的参数传递方式是『共享传参』(call by sharing)多数面向对象语言都采用这一模式,包括Ruby.Smalltalk和Java(Jav ...

  3. shell脚本的命令行传参

    在Linux环境下开发C程序,若想要可选择性的给程序传递外部参数,最后是以启动脚本的形式间接进行传递,这样对于命令行的参数解析工作将集中到shell脚本中,大大增加C代码的可移植性.       sh ...

  4. Linux C程序命令行传参

    在命令行环境下,执行已编译的程序时,将命令行参数以同一行的附加参数的形式传入到要执行的程序中.C编译器允许main()函数没有参数,或者有两个参数(也有可能更多,是对标准的扩展).一般形式为" ...

  5. Python 命令行传参

    Python 命令行传参 说到 python 命令行传参,可能大部分人的第一反应就是用 argparse.的确,argparse 在我们需要指定多个预设的参数(如深度学习中指定模型的超参数等)时,是非 ...

  6. argparse:Python命令行传参

    诸神缄默不语-个人CSDN博文目录 argparse模块(Python官方文档:argparse - 命令行选项.参数和子命令解析器 - Python 3.10.3 文档),可以用来在用命令行运行Py ...

  7. pytest命令行传参

    前言 命令行参数是根据命令行选项将不同的值传递给测试函数,比如平常在cmd执行"pytest --html=report.html",这里面的"--html=report ...

  8. Day13-Java方法详解,方法的定义、重载,命令行传参,可变参数与递归

    Java方法详解 什么是方法? Java的方法是语句的集合,他们在一起执行一个功能 方法是解决一类问题的步骤的有序组合 方法包含于类或对象中 方法再程序中被创建,在其他地方被引用 [方法原子性]一个方 ...

  9. python使用argparse模块实现在终端命令行传参

    直接上代码 import argparse # 定义终端要传送的参数 parser = argparse.ArgumentParser(description="A description ...

最新文章

  1. 解禁 115 天,中兴事件的“反思”中藏着什么?
  2. Hadoop生态hive(二)安装
  3. Java IO/NIO教程
  4. 工程实践:基于规则模式的军事和医药领域知识图谱问答快速实现
  5. 内核同步机制-读写信号量(rw_semaphore)
  6. C++多线程编程 (1)
  7. python用户界面画图_通过海龟绘图学习Python-01
  8. 移动端布局,C3新增属性
  9. 有了WCF,Socket是否已人老珠黄?
  10. 军用设备环境试验GJB150A-2009检测报告机构
  11. 计算机思维ppt模板,制作PPT思维导图模板分享
  12. abb机器人编程指令写字_ABB机器人编程指令与函数
  13. 网络推广能给企业公司带来什么好处?
  14. 2020年 初赛真题
  15. excel操作系列之中文姓名转英文姓名
  16. Python之数据库编程
  17. BT下载到底是什么意思啊?
  18. 新品密集!2020中关村论坛技术交易大会-第二场新技术新产品首发活动圆满举行...
  19. 对于MSB8036 找不到 Windows SDK 版本10.0.17763.0。请安装所需的版本的 Windows SDK的问题
  20. 节日来临,欺诈邮件太多,如何破

热门文章

  1. 51单片机数字电子钟设计(数电课设,含时间显示、校准、整点报时、闹钟功能)
  2. matlab 电路频率响应_2020年中青杯全国大学生数学建模竞赛——A题 集成电路通道布线...
  3. 在计算机里无法打开光盘,dvd光盘在win10电脑上打不开怎么回事?光盘放进电脑读不出来的修复方法...
  4. 未来SEO的发展方向是如何
  5. Qt之connect函数—信号槽连接的几种方式和优缺点
  6. 黑马程序员——开发工具——Eclipse
  7. C语言的sizeof运算符计算结构体大小
  8. 图数据库的易用性—GES与Flink的对接
  9. 干货|一文读懂 Spring Data Jpa!
  10. 【SSM整合】SSM详细整合-maven分模块架构