gpt4 book ai didi

python - python中的 'argv'是否总是使用脚本名称作为第一个参数?

转载 作者:行者123 更新时间:2023-12-01 04:36:20 27 4
gpt4 key购买 nike

Python 中的“argv”是否始终使用脚本名称作为第一个参数?如何避免?

例如,我将调用此sample.py:

from sys import argv

one, two, three = argv

print "My first number is ", one
print "My second number is ", two
print "My third number is ", three

当输入终端时

python sample.py one two three

它返回:

ValueError: too many values to unpack

当进入终端时:

python sample.py one two

它返回:

python seq1.py ONE TWO 
My first number is seq1.py
My second number is ONE
My third number is TWO
  • 在终端中运行时,能否避免第一个变量始终分配给脚本名称?
  • 有没有办法只输入和使用您想要的变量而无需脚本名称?或者甚至以某种方式“静音”带有脚本名称的废弃行的打印?

最佳答案

你可以做到

argv[1:]

获得不带文件名的参数列表。

它的作用是对 argv 列表进行切片并返回一个没有第一个元素的新列表。您可以阅读有关列表切片的更多信息 here

这是一个例子

from sys import argv

one, two, three = argv[1:]

print "My first number is ", one
print "My second number is ", two
print "My third number is ", three

关于python - python中的 'argv'是否总是使用脚本名称作为第一个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31622068/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com