命令行参数_Python 笔记_20190628

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/daoxu_hjl/article/details/93957551

1. argparse 按名称读取命令行参数

如何传递参数给Python 脚本,python 如何获取参数值,详见

argparse — Parser for command-line options, arguments and sub-commands

初始化: parser = argparse.ArgumentParser() --> 增加参数:
parser.add_argument(argument_info) : 只有一个参数可以不加"-",其余的必须加 “-” --> 解析参数 : parser.parse_args() --> 获取参数: args.file…
–> 程序使用:下面2种调用程序传参方式都可以,不需要指定顺序

python ascii.py “微信截图_20190627073701.png” -o result2.txt --width 100 --height 100 --width 100

python ascii.py --width 100 --height 100 --width 100 “微信截图_20190627073701.png” -o result2.txt

#命令行输入参数处理
parser = argparse.ArgumentParser()

parser.add_argument('file')     #输入文件
parser.add_argument('-o', '--output')   #输出文件
parser.add_argument('--width', type = int, default = 80) #输出字符画宽
parser.add_argument('--height', type = int, default = 80) #输出字符画高

#获取参数
args = parser.parse_args()
print(args.file)
print(args.output)
print(args.width)
print(args.height)

IMG = args.file
WIDTH = args.width
HEIGHT = args.height
OUTPUT = args.output

2. sys.argv 按顺序读取命令行参数

sys.argv[0] 读取python文件本身名称
sys.argv[1] 读取传入的第一个参数
sys.argv[2] 读取传入的第二个参数,以此类推

The list of command line arguments passed to a Python script. argv[0] is the script name (it is operating system dependent whether this is a full pathname or not). If the command was executed using the -c command line option to the interpreter, argv[0] is set to the string ‘-c’. If no script name was passed to the Python interpreter, argv[0] is the empty string.

https://docs.python.org/3.7/library/sys.html#module-sys


import sys

#参数验证
if len(sys.argv) < 3:
    print("Usage: python ",sys.argv[0]," file1 file2")
    sys.exit(1) # 程序异常退出

f1 = open(sys.argv[1])  # 只读模式打开file1
s = f1.read() # 读取file1,将字节内容赋值给s
f1.close  # 关闭file1

f2 = open(sys.argv[2],'w') # 写入模式打开file2
#f2.write(s)  # 将s中存储的file1的内容 写入f2
f2.close # 关闭 f2

import sys
print("First value", sys.argv[0])
print("All values")
for i, x  in enumerate(sys.argv):
    print(i, x)

猜你喜欢

转载自blog.csdn.net/daoxu_hjl/article/details/93957551