问题描述
我没有得到该程序的期望输出吗?
I am not getting desired output of this program?
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)
如何使用cmd传递这些参数?
How to use cmd to pass these arguments?
推荐答案
您称呼它为
python program.py a1 b2 c3
它会输出
The script is called: /home/sophia/program.py
Your first variable is: a1
Your second variable is: b2
Your third variable is: c3
sys.argv
包含字符串列表,每个字符串对应于一个命令行参数.第一个始终是脚本的文件名;其他是可选参数,其顺序与在shell中键入的顺序完全相同.
sys.argv
contains list of strings, each corresponding to a command line parameter. First one is always the filename of the script; others are the optional parameters, ordered exactly as they were typed in a shell.
请注意,由于元组解包,您恰好传递了三个参数时,您提供的代码仅能正确地正常工作.
Note that the code you provided works correctly only when you pass exactly three parameters due to the tuple unpacking.
请参阅 sys.argv 的文档,并检查如果要编写一个处理大量参数的程序,请参见 argparse模块文档.
See the docs for sys.argv and also check out argparse module documentation if you are going to write a program handling lots of arguments.
这篇关于如何在Python 3.x中传递命令行参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!