深度阅读

How to use sys.argv in Python

作者
作者
2023年08月22日
更新时间
8.29 分钟
阅读时间
0
阅读量

To use sys.argv in Python, you first need to import the sys module. Then you can access the command-line arguments passed to the script as elements in the sys.argv list.

Here’s an example:

import sys

# Print the total number of command line arguments
print("Total arguments: ", len(sys.argv))

# Print the command line arguments
for i, arg in enumerate(sys.argv):
    print("Argument", i, ":", arg)

When this code is executed with the command python myscript.py arg1 arg2 arg3, the output will be:

Total arguments: 4
Argument 0: myscript.py
Argument 1: arg1
Argument 2: arg2
Argument 3: arg3

As you can see, sys.argv[0] contains the name of the script itself, while subsequent elements contain the command-line arguments.

I hope this helps! Let me know if you have any further questions.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。