Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
308 views
in Technique[技术] by (71.8m points)

python - 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

I have searched online and tried to understand what sys.arg means, and here is my understanding:

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?

Also, if I run the code (press F5), the Python shell give me an error like:

Traceback (most recent call last):

File "C:Usersestcode.py", line 55, in <module>
init_pop_a, init_pop_b, tstep, tfinal = things
ValueError: need more than 0 values to unpack

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ...

This would result in your variables being:

Omega_a = 'arg1'
Omega_b = 'arg2'
Delta_a = 'arg3'
Delta_b = 'arg4'
init_pop_a = 'and'
init_pop_b = 'so'
tstep = 'on'
tfinal = '...'

While the input()s are given when the program is running.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...