【问题标题】:Variables in Python functions on RPiRPi 上 Python 函数中的变量
【发布时间】:2017-10-01 23:21:47
【问题描述】:

sudo python yantest.py 255,255,0

who = sys.argv[1]
print sys.argv[1]
print who
print 'Number of arguments:', len(sys.argv), 'arguments.'
print 'Argument List:', str(sys.argv)
yanon(strip, Color(who))  

上面的输出是

255,255,0

255,255,0

Number of arguments: 2 arguments.

Argument List: ['yantest.py', '255,255,0']

Traceback (most recent call last):
  File "yantest.py", line 46, in <module>
    yanon(strip, Color(who))
TypeError: Color() takes at least 3 arguments (1 given)
Segmentation fault

如何在 Color 函数中使用变量“who”?

我试过 ('who'), ("who") 都不管用。

【问题讨论】:

  • 我们不知道 Color 是什么,但根据错误,它期望 3 个 argent,但您只传递了一个:who
  • who = 255,255,0 这是它需要的 3 个参数。颜色(谁)似乎没有转换为变量的内容。
  • 不,实际上是who == "255,255,0",但这并不能真正解决我的评论
  • 是的,确实如此。 who是一个字符串"255,255,0"。您将其作为单个参数传递。但是,看起来 Color 需要三个 int 参数
  • 你是对的。我将字符串拆分为 ,然后转换为 int 。谢谢

标签: python raspberry-pi led


【解决方案1】:
TypeError: Color() takes at least 3 arguments (1 given)

错误意味着你应该传递 3 个参数,但你只传递了 1 个参数。这里有两种实现方式:

color_r = sys.argv[1]
color_g = sys.argv[2]
color_b = sys.argv[3]
yanon(strip, Color(color_r, color_g, color_b))  

运行脚本为:

sudo python yantest.py 255 255 0

who = sys.argv[1].split(',')
yanon(strip, Color(who[0], who[1], who[2]))  

运行脚本为:

sudo python yantest.py 255,255,0

而且你应该关心参数的类型!

【讨论】:

  • 这很好用。谢谢。我也必须转换为 int。所以这条线是 yanon(strip, Color(int(who[0]), int(who[1]), int(who[2]))) 不知道为什么不赞成。完美运行。
【解决方案2】:

谁是一个字符串。我不知道应该得到什么类型的可变颜色,但可能是 int。你应该用 "," 将 who 字符串拆分为 3 个子字符串,并将每个字符串转换为 int 或任何它应该是的。

【讨论】:

    猜你喜欢
    • 2017-03-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-15
    • 2015-09-04
    • 2019-04-18
    • 2013-07-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多