浅谈Python之sys.argv

本文详细解析了Python中sys.argv的功能,解释了如何通过命令行参数传递信息到脚本,以及sys.argv在脚本中的使用方式。通过实例展示了如何读取并打印sys.argv中的元素。

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

(1)sys.argv是什么

sys模块为进入解释器维护或使用的变量,以及与解释器相关的函数提供了途径。sys.argv在脚本程序中扮演了这样一个角色:将命令行输入的参数作为一个list传入脚本程序,即我们可以在cmd命令形式驱动程序方法下,将设定的参数传入脚本,argv[0]是驱动脚本的名字(由操作系统来决定是否是全路径的名字),如果cmd中,将-c传入,那么argv[0]就是-c,

分界线中的内容为cmd驱动脚本的详细解释,而关于cmd,-c传入的栗子,本文不再赘述  详见https://jingyan.baidu.com/article/03b2f78c3b38f05ea237ae05.html

在解释中,我们看到py [launcher-args] [python-args] script [script-args],这里script是脚本名字,而其后的[script-args]正是要传入脚本中sys.argv的列表,从argv[1]开始。下面举个简单的例子:

import sys
a=sys.argv[0]
b=sys.argv[1]
c=sys.argv[2]
print('argv0:%s'% a)
print('argv1:%s'% b)
print('argv2:%s'%c)

以上代码命名为sys_argvTest.py

然后在cmd中运行:

可以看到在脚本名字 后面的'thisisargv1' 'thisisargv2'分别传入了脚本中的sys.argv[1],sys.argv[2]中

---------------------------------------------------------------------------------------这是一道华丽的分界线--------------------------------------------------------------------------------------------------------------------------

usage:
py [launcher-args] [python-args] script [script-args]
Launcher arguments:
-2     : Launch the latest Python 2.x version
-3     : Launch the latest Python 3.x version
-X.Y   : Launch the specified Python version
     The above all default to 64 bit if a matching 64 bit python is present.
-X.Y-32: Launch the specified 32bit Python version
-X-32  : Launch the latest 32bit Python X version
-X.Y-64: Launch the specified 64bit Python version
-X-64  : Launch the latest 64bit Python X version
-0  --list       : List the available pythons
-0p --list-paths : List with paths
The following help text is from Python:
usage: C:\Users\Options and arguments (and corresponding environment variables):
-b     : issue warnings about str(bytes_instance), str(bytearray_instance)
         and comparing bytes/bytearray with str. (-bb: issue errors)
-B     : don't write .pyc files on import; also PYTHONDONTWRITEBYTECODE=x
-c cmd : program passed in as string (terminates option list)
-d     : debug output from parser; also PYTHONDEBUG=x
-E     : ignore PYTHON* environment variables (such as PYTHONPATH)
-h     : print this help message and exit (also --help)
-i     : inspect interactively after running script; forces a prompt even
         if stdin does not appear to be a terminal; also PYTHONINSPECT=x
-I     : isolate Python from the user's environment (implies -E and -s)
-m mod : run library module as a script (terminates option list)
-O     : remove assert and __debug__-dependent statements; add .opt-1 before
         .pyc extension; also PYTHONOPTIMIZE=x
-OO    : do -O changes and also discard docstrings; add .opt-2 before
         .pyc extension
-q     : don't print version and copyright messages on interactive startup
-s     : don't add user site directory to sys.path; also PYTHONNOUSERSITE
-S     : don't imply 'import site' on initialization
-u     : force the stdout and stderr streams to be unbuffered;
         this option has no effect on stdin; also PYTHONUNBUFFERED=x
-v     : verbose (trace import statements); also PYTHONVERBOSE=x
         can be supplied multiple times to increase verbosity
-V     : print the Python version number and exit (also --version)
         when given twice, print more information about the build
-W arg : warning control; arg is action:message:category:module:lineno
         also PYTHONWARNINGS=arg
-x     : skip first line of source, allowing use of non-Unix forms of #!cmd
-X opt : set implementation-specific option
--check-hash-based-pycs always|default|never:
    control how Python invalidates hash-based .pyc files
file   : program read from script file
-      : program read from stdin (default; interactive mode if a tty)
arg ...: arguments passed to program in sys.argv[1:]
Other environment variables:
PYTHONSTARTUP: file executed on interactive startup (no default)
PYTHONPATH   : ';'-separated list of directories prefixed to the
               default module search path.  The result is sys.path.
PYTHONHOME   : alternate <prefix> directory (or <prefix>;<exec_prefix>).
               The default module search path uses <prefix>\python{major}{minor}.
PYTHONCASEOK : ignore case in 'import' statements (Windows).
PYTHONIOENCODING: Encoding[:errors] used for stdin/stdout/stderr.
PYTHONFAULTHANDLER: dump the Python traceback on fatal errors.
PYTHONHASHSEED: if this variable is set to 'random', a random value is used
   to seed the hashes of str, bytes and datetime objects.  It can also be
   set to an integer in the range [0,4294967295] to get hash values with a
   predictable seed.
PYTHONMALLOC: set the Python memory allocators and/or install debug hooks
   on Python memory allocators. Use PYTHONMALLOC=debug to install debug
   hooks.
PYTHONCOERCECLOCALE: if this variable is set to 0, it disables the locale
   coercion behavior. Use PYTHONCOERCECLOCALE=warn to request display of
   locale coercion and locale compatibility warnings on stderr.
PYTHONBREAKPOINT: if this variable is set to 0, it disables the default
   debugger. It can be set to the callable of your debugger of choice.
PYTHONDEVMODE: enable the development mode.
---------------------------------------------------------------------------------------这是一道华丽的分界线-------------------------------------------------------------------------------------------------------------------------

转载于:https://www.cnblogs.com/johnyang/p/10479868.html

<think>好的,用户想了解Pythonsys.argv的含义和用法。首先,我需要回忆sys.argv的基本概念。根据引用资料,sys.argv是一个列表,用于从命令行接收参数。第一个元素是脚本名,后面的元素是传入的参数。用户可能想知道如何访问这些参数,如何处理参数不足的情况,以及实际应用场景。 接下来,要确保回答结构清晰。先解释sys.argv是什么,再说明它的组成,比如sys.argv[0]是脚本名,sys.argv[1]开始是参数。然后给出一个简单的例子,比如如何打印参数。引用中提到了检查参数长度,这很重要,所以需要提醒用户处理参数不足的情况,避免索引错误。 用户可能对实际应用感兴趣,比如在自动化脚本中根据参数执行不同操作。例如,处理文件路径或者配置选项。引用中的示例代码可以作为参考,但需要简化,用中文注释解释每行代码的作用。 此外,需要注意常见问题,比如参数类型都是字符串,需要转换,以及如何处理带空格的参数。这些细节能帮助用户避免常见错误。最后,生成相关问题,帮助用户深入理解,比如参数解析库或最佳实践。 要确保回答符合格式要求,行内公式用$...$,代码块用正确格式。同时检查引用标记是否正确添加,比如参数检查部分引用[^2]。避免使用Markdown,保持自然的中文表达,分步骤解释,让用户容易理解。</think>### Pythonsys.argv的含义及用法解析 #### 一、sys.argv的定义 `sys.argv`是Python内置模块`sys`提供的列表,用于**接收命令行参数**。其特点包括: 1. 参数类型:所有元素均为字符串 2. 元素顺序: - `sys.argv[0]`:当前执行的脚本文件名 - `sys.argv[1]`:第一个命令行参数 - 依此类推,`sys.argv[n]`表示第n个参数 #### 二、基础用法示例 ```python # file: demo.py import sys print("脚本名称:", sys.argv[0]) print("参数数量:", len(sys.argv)-1) print("参数列表:", sys.argv[1:]) ``` 执行命令及输出: ```bash $ python demo.py apple 123 "hello world" 脚本名称: demo.py 参数数量: 3 参数列表: ['apple', '123', 'hello world'] ``` #### 三、关键使用技巧 1. **参数校验**(必须操作) 必须检查参数数量以避免`IndexError`[^2]: ```python if len(sys.argv) < 2: print("Usage: python script.py <参数>") sys.exit(1) ``` 2. **参数类型转换** 所有参数默认是字符串类型,需要显式转换: ```python num = int(sys.argv[2]) # 转换为整数 ``` 3. **路径处理** 当参数包含文件路径时建议使用`os.path`模块: ```python import os file_path = os.path.abspath(sys.argv[1]) ``` #### 四、实际应用场景 1. 自动化脚本参数配置(如指定日志级别`--debug`) 2. 批处理文件路径输入 3. 算法参数动态调整(如机器学习模型训练时指定学习率) #### 五、注意事项 - 带空格的参数需用引号包裹 - 建议使用`argparse`模块处理复杂参数需求 - 参数索引从1开始(sys.argv[0]始终为脚本名)[^3]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值