如何在Python 3.x中传递命令行参数?

Inq*_*eSu 17 python-3.x

我没有得到这个程序的期望输出?

from sys import argv

script, first, second, third = argv

print ("The script is called:", script)
print ("Your first variable is:", first)
print ("Your second variable is:", second)
print ("Your third variable is:", third)
Run Code Online (Sandbox Code Playgroud)

如何使用cmd传递这些参数?

Tig*_*uev 24

你称之为

python program.py a1 b2 c3
Run Code Online (Sandbox Code Playgroud)

它输出

The script is called: /home/sophia/program.py
Your first variable is: a1
Your second variable is: b2
Your third variable is: c3
Run Code Online (Sandbox Code Playgroud)

sys.argv包含字符串列表,每个字符串对应一个命令行参数.第一个始终是脚本的文件名; 其他是可选参数,完全按照在shell中键入的顺序排序.

请注意,只有在由于元组解包而传递了三个参数时,您提供的代码才能正常工作.

如果要编写处理大量参数的程序,请参阅sys.argv的文档并查看argparse模块文档.