博客园  :: 首页  :: 管理

关于python中对sys.argv的理解

Posted on 2021-09-30 12:27  520_1351  阅读(212)  评论(0编辑  收藏  举报

在python中,如果需要从命令行接收参数,比较常用的方法,就是使用sys模块中的argv,返回的结果是一个列表

对于arvg可以理解成argument variable的缩写(也有称是argument value的缩写,个人更倾向于理解成 argument variable)

sys.argv 官网的说明如下: 

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.
To loop over the standard input, or the list of files given on the command line, see the fileinput module.

Note
On Unix, command line arguments are passed by bytes from OS.
Python decodes them with filesystem encoding and “surrogateescape” error handler. When you need original bytes,
you can get it by [os.fsencode(arg) for arg in sys.argv].

在使用前需要先导入sys模块,如下,创建一个sys_argv.py文件:

#!/usr/bin/env python3
#

import sys

print(sys.argv)

执行python3  ./sys_argv.py   qq   5201351,结果如下:

['./sys_argv.py', 'qq', '5201351']

 

 

尊重别人的劳动成果 转载请务必注明出处:https://www.cnblogs.com/5201351/p/15356175.html