“sys.argv"是什么意思? [英] What does 'sys.argv' mean?
问题描述
我正在从代码中学习,但我对其中的一行代码感到困惑:
I am learning from code, and I am get confused by one of its lines which is:
things = [float(arg) for arg in sys.argv[1:]]
Omega_a, Omega_b, Delta_a, Delta_b, \
init_pop_a, init_pop_b, tstep, tfinal = things
我在网上搜索并试图理解 sys.arg
的含义,以下是我的理解:
I have searched online and tried to understand what sys.arg
means, and here is my understanding:
所以 sys.argv[0]
是文件名,而 sys.argv[1:]
是其余的参数,应该由用户给出.我不确定我的理解是否正确,如果是,那么我不明白为什么不能这样:
So sys.argv[0]
is the file name, and sys.argv[1:]
is the rest of the parameters which should given by users. I am not sure am I understood it right, and if it is, then I don't understand why cant it be like:
Omega_a = input()
Omega_b = input()
etc...
这两种给定参数的方式有什么区别?
What's the difference between these two ways of giving parameters?
此外,如果我运行代码(按 F5),Python shell 会出现如下错误:
Also, if I run the code (press F5), the Python shell give me an error like:
Traceback (most recent call last):
File "C:\Users\testcode.py", line 55, in <module>
init_pop_a, init_pop_b, tstep, tfinal = things
ValueError: need more than 0 values to unpack
在它给我一个错误之前,我什至没有机会给出参数 (sys.argv[1:]
).于是上网查了一下.看起来我需要在 cmd 中运行这段代码,这让我更加困惑,为什么要这样做以及我应该如何放入 cmd 才能运行它?
I wasn't even given a chance to give parameters (sys.argv[1:]
) before it gave me an error. So I searched online. It looks like I need to run this code in cmd which confused me more, why should it and how should I put into cmd in order to run it?
推荐答案
不同的是,sys.argv
(命令行)参数是在程序运行前(启动时)给出的:
The difference is, that sys.argv
(command line) parameters are given before the program is running (while starting it):
python testcode.py arg1 arg2 arg3 arg4 and so on ...
这将导致您的变量为:
Omega_a = 'arg1'
Omega_b = 'arg2'
Delta_a = 'arg3'
Delta_b = 'arg4'
init_pop_a = 'and'
init_pop_b = 'so'
tstep = 'on'
tfinal = '...'
虽然 input()
是在程序运行时给出的.
While the input()
s are given when the program is running.
由于您没有使用参数启动程序,因此会出现错误,因为没有足够的(恰好 0 个)参数可以解压到变量中.
As you do not start the program with parameters it gives you the error, because there are not enough (exactly 0) parameters to be unpacked into the variables.
这篇关于“sys.argv"是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!