菜鸟教程 -- 学的不仅是技术,更是梦想!

Python 3 教程
Python3 教程 Python3 简介 Python3 环境搭建 Python3 VScode Python3 基础语法 Python3 基本数据类型 Python3 数据类型转换 Python3 解释器 Python3 注释 Python3 运算符 Python3 数字(Number) Python3 字符串 Python3 列表 Python3 元组 Python3 字典 Python3 集合 Python3 条件控制 Python3 循环语句 Python3 编程第一步 Python3 推导式 Python3 迭代器与生成器 Python3 with Python3 函数 Python3 lambda Python3 装饰器 Python3 数据结构 Python3 模块 Python __name__ Python3 输入和输出 Python3 File Python3 OS Python3 错误和异常 Python3 面向对象 Python3 命名空间/作用域 Python 虚拟环境的创建 Python 类型注解 Python3 标准库概览 Python3 实例 Python 测验

Python3 高级教程

Python3 正则表达式 Python3 CGI编程 Python3 MySQL(mysql-connector) Python3 MySQL(PyMySQL) Python3 网络编程 Python3 SMTP发送邮件 Python3 多线程 Python3 XML 解析 Python3 JSON Python3 日期和时间 Python3 内置函数 Python3 MongoDB Python3 urllib Python uWSGI 安装配置 Python3 pip Python3 operator Python math Python requests Python random Python OpenAI Python 有用的资源 Python AI 绘画 Python statistics Python hashlib Python 量化 Python pyecharts Python selenium 库 Python 爬虫 Python Scrapy 库 Python Markdown Python sys 模块 Python Pickle 模块 Python subprocess 模块 Python queue 模块 Python StringIO 模块 Python logging 模块 Python datetime 模块 Python re 模块 Python csv 模块 Python threading 模块 Python asyncio 模块 Python PyQt Python for 循环 Python while 循环
(追記) (追記ここまで)

Python3 命令行参数

Python3 基础语法 Python3 基础语法

Python 提供了 getopt 模块来获取命令行参数。

$ python test.py arg1 arg2 arg3

Python 中也可以所用 syssys.argv 来获取命令行参数:

  • sys.argv 是命令行参数列表。

  • len(sys.argv) 计算命令行参数个数。

注:sys.argv[0] 表示脚本名。

实例

test.py 文件代码如下:

实例

#!/usr/bin/python3

import sys

print ('参数个数为:', len(sys.argv), '个参数。')
print ('参数列表:', str(sys.argv))
print ('脚本名:', str(sys.argv[0]))

执行以上代码,输出结果为:

$ python3 test.py arg1 arg2 arg3
参数个数为: 4 个参数。
参数列表: ['test.py', 'arg1', 'arg2', 'arg3']
脚本名: test.py

getopt 模块

getopt 模块是专门处理命令行参数的模块,用于获取命令行选项和参数,也就是 sys.argv。命令行选项使得程序的参数更加灵活。支持短选项模式 - 和长选项模式 --

该模块提供了两个方法及一个异常处理来解析命令行参数。

getopt.getopt 方法

getopt.getopt 方法用于解析命令行参数列表,语法格式如下:

getopt.getopt(args, options[, long_options])

方法参数说明:

  • args: 要解析的命令行参数列表。

  • options: 以字符串的格式定义,options 后的冒号 : 表示该选项必须有附加的参数,不带冒号表示该选项不附加参数。

  • long_options: 以列表的格式定义,long_options 后的等号 = 表示如果设置该选项,必须有附加的参数,否则就不附加参数。

该方法返回值由两个元素组成: 第一个是 (option, value) 元组的列表。 第二个是参数列表,包含那些没有 --- 的参数。

接下来我们定义一个 site() 函数,然后通过命令行输入站点名称 name 和网址 url,可以用缩写 nu:

实例

import sys
import getopt


def site():
name = None
url = None

argv = sys.argv[1:]

try:
opts, args = getopt.getopt(argv, "n:u:") # 短选项模式

except:
print("Error")

for opt, arg in opts:
if opt in ['-n']:
name = arg
elif opt in ['-u']:
url = arg


print( name +" " + url)

site()

测试以上代码,命令行中输入:

python3 test.py -n RUNOOB -u www.runoob.com

输出结果为:

RUNOOB www.runoob.com

以下实例演示长选项模式的使用:

实例

import sys
import getopt

def site():
name = None
url = None

argv = sys.argv[1:]

try:
opts, args = getopt.getopt(argv, "n:u:",
["name=",
"url="]) # 长选项模式

except:
print("Error")

for opt, arg in opts:
if opt in ['-n', '--name']:
name = arg
elif opt in ['-u', '--url']:
url = arg


print( name + " " + url)

site()

测试以上代码,命令行中输入:

python3 test.py -n RUNOOB -u www.runoob.com

输出结果为:

RUNOOB www.runoob.com

另外一个方法是 getopt.gnu_getopt,用到的情况比较少,这里不多做介绍。


Exception getopt.GetoptError

在没有找到参数列表,或选项的需要的参数为空时会触发该异常。

异常的参数是一个字符串,表示错误的原因。属性 msgopt 为相关选项的错误信息。

实例

假定我们创建这样一个脚本,可以通过命令行向脚本文件传递两个文件名,同时我们通过另外一个选项查看脚本的使用。脚本使用方法如下:

usage: test.py -i <inputfile> -o <outputfile>

test.py 文件代码如下所示:

实例

#!/usr/bin/python3

import sys, getopt

def main(argv):
inputfile = ''
outputfile = ''
try:
opts, args = getopt.getopt(argv,"hi:o:",["ifile=","ofile="])
except getopt.GetoptError:
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit(2)
for opt, arg in opts:
if opt == '-h':
print ('test.py -i <inputfile> -o <outputfile>')
sys.exit()
elif opt in ("-i", "--ifile"):
inputfile = arg
elif opt in ("-o", "--ofile"):
outputfile = arg
print ('输入的文件为:', inputfile)
print ('输出的文件为:', outputfile)

if __name__ == "__main__":
main(sys.argv[1:])

执行以上代码,输出结果为:

$ python3 test.py -h
usage: test.py -i <inputfile> -o <outputfile>
$ python3 test.py -i inputfile -o outputfile
输入的文件为: inputfile
输出的文件为: outputfile

Python3 基础语法 Python3 基础语法

AI 思考中...

1 篇笔记 写笔记

  1. #0

    CAN

    yib***@qq.com

    参考地址

    782

    讲真的本页后面这个 getopt 方法看得我云里雾里的,后来看了官方文档终于明白了。这里斗胆重新写一下。

    官方的函数定义是这样子的,我觉得这样写清楚很多:

    getopt.getopt(args, shortopts, longopts=[])

    三个参数:

    • args: 这个很清楚,就是参数列表。直接把 sys.args[1:] 切片传进来就可以。
    • shortopts: 这个参数是个字符串,把需要解析的"短选项"挨着写在一起就可以,这里的"短选项"指的是以 '-' 开头的选项,叫短选项是因为这种选项只支持单个字母,就算你写 -test 这样子的参数,能被 getopt 识别出来的也是 -t 和 est,其中 est 会被当作 -t 选项的参数。所以假设你想支持 "-h -i -o" 三个短选项, shortopts 就可以写成 "hio"。如果其中某个短选项想要接受参数,比如 "-h -i inputfile -o outputfile",那就需要在字母后面加 ":" 冒号,变成 "hi:o:"
    • longopts=[]: 这个参数是个列表,因为每个长选项有多个字母,不可能像短选项一样用一个字符串就都表示出来。所谓长选项,就是以 "--" 开头的选项,比如 --usr --ifile --ofile 等,传参的时候写成 ['--user', '--ifile', '--ofile'],如果某个选项需要接受参数,则在后面加 "=" 等号,比如 ['--user', '--ifile=', '--ofile=']。

    返回值,有两个:

    • opts:是有一个列表,列表里是元组(opt, value)的格式。比如上面的 "-h -i inputfile -o outputfile" 那就是 [('-h', ''), ('-i', 'inputfile'), ('-o', 'outputfile')] 这样的返回值。长选项和短选项以及各自的参数都会按先后次序放在这里。用的时候可以以 for opt,val in opts: 这样的方式来遍历。值得注意的是,返回的 opt 里面,'-' 和 '--' 都被保留下来了,另外,当用户输入的长选项没有写完的时候,会被自动补全。比如用户输入的是 --u,通过 getopt 会被自动补全成 --user,这个需要注意(除非有两个长选项都有相同的开头,无法确定是哪个)。
    • args:如果用户输入的信息太多,除了长选项和短选项以及各自选项的参数以外,还有一些其它的未知的参数,则会被放到这里。 看了这些,再去看上面的例子,相信会清楚很多了

    写得比较啰嗦,希望对大家有用。

    CAN

    yib***@qq.com

    参考地址

    6年前 (2020年12月26日)

点我分享笔记

  • 昵称 (必填)
  • 邮箱 (必填)
  • 引用地址

AltStyle によって変換されたページ (->オリジナル) /