将不同命令的列表作为函数导入和调用

Importing and calling a list of different commands as functions

目前我正在尝试了解控制软件如何通过串行端口与 modem/DCE 通信。为此,我在 Python 中使用 PySerial。我设法被动地监听了两者的通信,并且确实有一个字节串列表(例如 b'\x1d\x10\xff')软件在执行几个单个操作时发送。

要完全理解我想要的命令结构和响应,请使用 试错法 并通过扩展我的 [=24] 用我自己的 PC 模拟控制软件=]-script 通过发送命令然后监听响应。现在我将这些命令定义为函数,例如:

def Testcommand1():
    if serial.isOpen() == True:
        serial.write(b'\x1d\x10\xff')
        print('Testcommand1 to do some specific stuff sent, awaiting response.')
    else:
        print('ERROR: Serial port is closed')

最后我会有 20-30 个不同的命令。我计划在不同的文件中定义它们并从那里调用它们。据我所知,为了调用它们,我需要单独导入每个函数,比如

from commandfile import Testcommand1()
from commandfile import Testcommand2()
from commandfile import Testcommand3()
...

这就是我开始怀疑我的方法的地方(因为在我开始实际的 'listen'-程序之前我会有 20-30 行):这真的是最好的方法吗?或者有没有像 def function() 这样更精巧更聪明的东西来定义我要发送的命令?

from commandfile import Testcommand1() 将不起作用。

from commandfile import Testcommand1 会。

您也可以将它们全部导入

from commandfile import *