【问题标题】:How to make x variable change each time and read its value from txt file如何使 x 变量每次更改并从 txt 文件中读取其值
【发布时间】:2019-12-30 11:11:15
【问题描述】:

我正在做我的本科项目,这是我第一次使用 Python 来控制 parrot bebop 2 无人机。我有一个变量x(an int),我想从文件中读取它的值。同时我希望程序连续读取这个文件;我的意思是我的文本文件输入每次都会更改,我希望 Python 代码能够捕捉到这种更改并更改值 x

例如:

  1. 如果 x 从文本文件中被赋值为 1 --> 那么无人机就会起飞。
  2. 同时在x被赋值1后,我希望它自动赋值2并执行第二个命令,例如:向左移动(但不断开无人机“第一个命令”)

这是我的代码,但我遇到了很多问题,它会检查值,但在知道x 的值后没有任何命令起作用:

bebop = Bebop()
print("connecting")
success = bebop.connect(10)
print(success) 
f = open('EEGresults.txt')
lines = f.readlines()
list_of_elements = []
for line in lines:
   list_of_elements += map(int, line.split())
f.close()
print (list_of_elements)
x = list_of_elements[1]

bebop.smart_sleep(5)

 if x == 1:
   print ("Yay! This number is = 1")
   bebop.safe_takeoff(3)

else:
   if x == 2:
      print ("Yay! This number is = 2")
      bebop.move_relative(0,0,0,1.6)

我希望代码会直接连续地从文本文件中读取x 的值,同时它会根据收到的x 的值运行命令。

【问题讨论】:

  • 你还没有定义函数Bebop(),所以python搜索它并没有找到任何东西,因此给你一个错误。
  • 现在不知道Bebop() 的主体是什么,除非人们知道该函数的逻辑,否则很难为您提供帮助。

标签: python-3.x windows if-statement controls parrot


【解决方案1】:

我不知道如何使用Bebop,但我应该使用这样的东西......

首先,我将创建一个对象来存储您文件中的数据。所以你需要一个类似onValueChanged 回调的东西。你必须自己定义这个对象:

class NotifierVariable():
    def __init__(self):
        self.__value = 0
        self.__Listener = list()

    @NotifierVariable.setter
    def set(self, value):
        if(value != self.__value):
            self.__value = value
            for callback in self.__Listener:
                callback(self.__value)

    @property
    def get(self):
        return self.__value


    def addListener(self, callback):
            self.__Listener.append(callback)

您可以通过以下方式使用它:

class NotifierVariable():
    def __init__(self):
        self.__value = 0
        self.__Listener = list()

    def set(self, value):
        if(value != self.__value):
            self.__value = value
            for callback in self.__Listener:
                callback(self.__value)

    def get(self):
        return self.__value


    def addListener(self, callback):
            self.__Listener.append(callback)


def Func(value):
    print(value)

if __name__ == '__main__':
    x = NotifierVariable()
    x.addListener(Func)
    x.set(10)

现在你必须定期读取文件:

while(True):

    with open('EEGresults.txt') as File:
        lines = File.readlines()
        list_of_elements = []
        for line in lines:
           list_of_elements += map(int, line.split())

        print (list_of_elements)
        x.set(list_of_elements[1])

    time.sleep(10)

您使用回调将命令发送到您的无人机。该文件每 10 秒定期读取一次(您可以更改它)并更新您的 x 变量。如果值发生更改,则会触发回调,然后您可以根据输入向您的无人机发送命令。

【讨论】:

    猜你喜欢
    • 2021-10-18
    • 1970-01-01
    • 1970-01-01
    • 2023-02-22
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多