【python】sys.argv[] 的用法

本文介绍Python中sys.argv的使用方法,包括如何通过命令行传递参数给Python脚本,并展示如何解析这些参数来实现脚本的功能扩展,如版本信息和帮助信息的输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

sys.argv[]是用来获取命令行参数的,sys.argv[0]表示代码本身文件路径,因此要从第二个即sys.argv[1]开始取参数。
注意:参数是以空格分开的
创建一个名为sysargv.py的文件,内容如下:
import sys

print('the first  argv: ',sys.argv[0],'\n')#显示第一个参数
print('the second argv: ',sys.argv[1],'\n')#显示第二个参数
print('the third  argv: ',sys.argv[2],'\n')#显示第三个参数,以此类推

执行的结果如下:。
E:\lib>learnsysargv.py yang.txt yangqilong

the first  argv:  E:\lib\learnsysargv.py  --pyython文件的路径

the second argv:  yang.txt   --参数1

the third  argv:  yangqilong --参数2

官方教材中的一个例子,我修改了一下
import sys
print('the first  argv: ',sys.argv[0])
print('the second argv: ',sys.argv[1])
#print('the third  argv: ',sys.argv[2])
if len(sys.argv) < 2:
    print ('No action specified.')
    sys.exit()
解释一下下面IF语句的语法:判断参数1是否是以‘--’开头
if sys.argv[1].startswith('--'):
    ption = sys.argv[1][2:]//把参数1从第三个字符开始的字符串赋值给  option(去掉‘--’字符),直到参数1后面的空格。
    # fetch sys.argv[1] but without the first two characters
    if ption == 'v':
        print ('Version 1.2')
    elif option == 'h':
       print ('This program prints files to the standard output.\nAny number of files can be specified.\n\
Options include:\n\
--v : Prints the version number\n\
--h : Display this help')
程序输出结果:
E:\lib>sysargv.py  --h
the first  argv:  E:\lib\sysargv.py
the second argv:  --h
This program prints files to the standard output.
Any number of files can be specified.
Options include:
--v : Prints the version number
--h : Display this help

E:\lib>sysargv.py  --v
the first  argv:  E:\lib\sysargv.py
the second argv:  --v
Version 1.2

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22664653/viewspace-703178/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/22664653/viewspace-703178/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值