How can Python retrieve command line arguments?
Python can utilize the sys module to retrieve command line arguments. Here are the specific steps:
- import the sys module
- You can use sys.argv to access command-line arguments, which is a list containing all the command-line arguments. The first element is the script’s name, followed by any additional arguments passed to the script.
- The first argument provided in the command line.
The example code is as follows:
import sys
# 打印所有的命令行参数
print(sys.argv)
# 获取第一个参数
arg1 = sys.argv[1]
print("第一个参数是:", arg1)
When running a Python script from the command line, you can pass arguments, for example python script.py arg1 arg2, where arg1 and arg2 are the command line parameters.