深度阅读

How to get the command line arguments in Python?

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

To get the command line arguments in Python, you can use the sys module. The sys.argv variable is a list in Python that contains the command-line arguments passed to the script. It can be indexed to access specific command-line arguments. Here’s an example:

import sys

# Get the command-line arguments
args = sys.argv

# Print the number of command-line arguments
print(f"Number of arguments: {len(args)}")

# Print each command-line argument
for arg in args:
    print(arg)

In this example, we import the sys module and then use sys.argv to get the command-line arguments. We print the number of arguments using the len() function, and then use a for loop to print each command-line argument.

Note that the first item in sys.argv is always the name of the script itself, so the actual command-line arguments start at index 1. If you need to access specific command-line arguments, you can do so by indexing into sys.argv, like this: sys.argv[1] for the first argument, sys.argv[2] for the second argument, and so on.

It’s worth noting that this method of parsing command-line arguments is not very flexible or robust. For more advanced command-line argument parsing, you may want to consider using the argparse module, which provides a more feature-rich way of parsing command-line arguments.

博客作者

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