将命令行参数传递给Python脚本会导致错误

时间:2013-04-19 23:46:19

标签: python

我有一些来自ADAFRUIT的python示例脚本控制伺服,它可以工作!

我想通过从命令行调用两个值来执行它来更改ServoMin和ServoMax值。我遇到的问题是,当我import sys并设置ServoMin = (sys.argv)时似乎不喜欢它。我不知道为什么它不接受int或str。有什么想法吗?

以下是代码正文:

#!/usr/bin/python

from Adafruit_PWM_Servo_Driver import PWM
import time
import sys

# ===========================================================================
# Example Code
# ===========================================================================

# Initialise the PWM device using the default address
# bmp = PWM(0x40, debug=True)
pwm = PWM(0x50, debug=True)

servoMin = 150  # Min pulse length out of 4096
servoMax = 600  # Max pulse length out of 4096

def setServoPulse(channel, pulse):
  pulseLength = 1000000                   # 1,000,000 us per second
  pulseLength /= 60                       # 60 Hz
  print "%d us per period" % pulseLength
  pulseLength /= 4096                     # 12 bits of resolution
  print "%d us per bit" % pulseLength
  pulse *= 1000
  pulse /= pulseLength
  pwm.setPWM(channel, 0, pulse)

pwm.setPWMFreq(60)                        # Set frequency to 60 Hz
while (True):
  # Change speed of continuous servo on channel O
  pwm.setPWM(0, 0, servoMin)
  time.sleep(1)
  pwm.setPWM(0, 0, servoMax)
  time.sleep(1)

1 个答案:

答案 0 :(得分:2)

sys.argv是参数列表,您需要访问参数,然后将它们转换为Ints。

这应该这样做:

servoMin = int(sys.argv[1])
servoMax = int(sys.argv[2])