-1

我从 github 复制此代码并尝试在 python 上运行它。我收到以下错误。我是 python 和树莓派的新手。请有人解决这个问题?

错误:

if(bool(sys.argv[1]) 和 bool(sys.argv[2])): IndexError: 列表索引超出范围

编码:

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()
4

2 回答 2

3

sys.argv contains a list of the command line arguments used to call the script, the first element of which will always be the name of your script. If you call the script without any arguments, it will only contain one element.

Since your code doesn't check to ensure it contains at least three element, calling the script with fewer than two arguments will try to access elements not in the list, raising the exception you see.

于 2013-08-29T11:11:06.310 回答
0

sys.argv是传递给 python 脚本的命令行参数列表。argv[0] 是脚本名称,argv[1] 第一个 arg 等等...看起来您正在调用脚本而没有传递所需的参数。

于 2013-08-29T11:11:36.073 回答