2013-08-29 93 views
-1

我從github複製此代碼並嘗試在python上運行它。我得到了以下錯誤。我新來蟒蛇和覆盆子pi。請有人解決這個問題嗎?python:IndexError:列表索引超出範圍

錯誤:

if(bool(sys.argv[1]) and bool(sys.argv[2])): IndexError: list index out of range

編碼:

import time 
import RPi.GPIO as GPIO 
import sys 

GPIO.cleanup() 

GPIO.setmode(GPIO.BCM) 



Passed = 0 


pulseWidth = 0.01 


if(bool(sys.argv[1]) and bool(sys.argv[2])): 

    try: 
     motorPin = int(sys.argv[1]) 
     runTime = float(sys.argv[2]) 
     powerPercentage = float(sys.argv[3])/100 
     Passed = 1 
    except: 
     exit 

if Passed: 

    # Set all pins as output 
    print "Setup Motor Pin" 
    GPIO.setup(motorPin,GPIO.OUT) 
    GPIO.output(motorPin, False) 
    counter = int(runTime/pulseWidth) 

    print "Start Motor" 

    print "Power: " + str(powerPercentage) 
    onTime = pulseWidth * powerPercentage 
    offTime = pulseWidth - onTime 

    while counter > 0: 
     GPIO.output(motorPin, True) 
     time.sleep(onTime) 
     GPIO.output(motorPin, False) 
     time.sleep(offTime) 
     counter = counter - 1 

    print "Stop Motor" 
    GPIO.output(motorPin, False) 


else: 
     print "Usage: motor.py GPIO_Pin_Number Seconds_To_Turn Power_Percentage" 

GPIO.cleanup() 
+2

而你*做*傳遞至少兩個參數的腳本? –

+0

'sys.argv [2]'列表可能有<3條目 – suhailvs

+1

'sys.argv [1]'和'sys.argv [2]'如果您將兩個參數傳遞給腳本, –

回答

2

sys.argv包含用於調用腳本的命令行參數列表,第一個元素,其中將永遠是你的腳本的名稱。如果你沒有任何參數調用腳本,它將只包含一個元素。

由於您的代碼不檢查以確保它至少包含三個元素,因此使用少於兩個參數調用腳本將嘗試訪問不在列表中的元素,引發您看到的異常。

0

sys.argv是傳遞給python腳本的命令行參數列表。 argv [0]是腳本名稱,argv [1]第一個參數等等...看起來像是在不傳遞所需參數的情況下調用腳本。