简体   繁体   English

关于sys.argv的新手Python问题

[英]Newbie Python question about sys.argv

I'm currently going through a few tutorials to get myself up and running on Python, but I seem to hit the same problem a few times. 我目前正在阅读一些教程,以使自己入门并在Python上运行,但似乎几次遇到相同的问题。 The tutorial I'm currently following is Aloha.py in Introduction to Simulation by Norm Matloff. 我当前正在关注的教程是Norm Matloff撰写的《 模拟简介》中的Aloha.py。

The problem I'm hitting seems to be in the following code: 我遇到的问题似乎在以下代码中:

import random, sys
class node: # one object of this class models one network node
# some class variables
    s = int(sys.argv[1]) # number of nodes

The error message when I try and run the programme is: 当我尝试运行该程序时,错误消息是:

Traceback (most recent call last):
  File "C:\Python26\Aloha.py", line 8, in <module>
    class node:
  File "C:\Python26\Aloha.py", line 10, in node
    s = int(sys.argv[0])
ValueError: invalid literal for int() with base 10: 'C:\\Python26\\Aloha.py'

I've worked out that sys.argv[1] doesn't exist when I try and run the program, so does anyone know where I might be going wrong? 我已经确定,当我尝试运行该程序时sys.argv[1]不存在,所以有人知道我可能会出错吗? Is there some way of starting the program that will set these values or is my system somehow set up incorrectly? 是否有某种方法可以启动将设置这些值的程序,或者我的系统设置不正确?

The traceback shows that you actually have this in your code: 追溯显示您的代码中确实包含以下内容:

s = int(sys.argv[0])

so you are referring to argument 0 - the script name itself - rather than 1. 因此,您指的是参数0-脚本名称本身-而不是1。

sys.argv is for collecting the options given to the program on the command-line. sys.argv用于收集在命令行上给程序的选项。 So instead of just running the file, you'll want to run python aloha.py 5 (or whatever number you want). 因此,您不仅要运行文件,还需要运行python aloha.py 5 (或任何您想要的数字)。

(Otherwise, you could just set the number directly in the code instead of always expecting it on the command-line, as in s = 5 for example.) (否则,您可以直接在代码中直接设置数字,而不必总是在命令行中期望它,例如s = 5 。)

Also, to load in command line arguments when you run a program you'd want to run your program like this... 另外,要在运行程序时加载命令行参数,您需要这样运行程序...

python Aloha.py 75

Where 75 is replaced by the number of nodes. 其中75替换为节点数。 75 will then become argv[1] . 75将成为argv[1]

尝试

s = int(sys.argv[-1])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM