Python 如何添加for循环以减少此代码?

Python 如何添加for循环以减少此代码?,python,Python,此代码用于设置系统(我向系统发送命令以使其闪烁,但首先我需要通过逐个命令发送命令并读取系统的输出来设置环境,以查看我发送的命令是否得到良好的解释)。我需要优化它 优化此代码最优雅的方式是什么?我正在考虑添加一个包含所有命令的数组,然后将它们放入for循环!! 请分享你的想法 try: ser = serial.Serial("COM32", baudrate=115200, timeout=0, stopbits=serial.STOPBITS_ONE) if ser.isOpen():

此代码用于设置系统(我向系统发送命令以使其闪烁,但首先我需要通过逐个命令发送命令并读取系统的输出来设置环境,以查看我发送的命令是否得到良好的解释)。我需要优化它

优化此代码最优雅的方式是什么?我正在考虑添加一个包含所有命令的数组,然后将它们放入for循环!! 请分享你的想法

try:
  ser = serial.Serial("COM32", baudrate=115200, timeout=0, stopbits=serial.STOPBITS_ONE)
  if ser.isOpen():
      print(ser.name + ' is open...')
  else:
      print(ser.name + ' is closed...')

  if command1  == 'exit' or command2 == 'exit' or command3 == 'exit' or command4 == 'exit' or command5 == 'exit' or command6 == 'exit' :

      ser.close()
      exit()
  else:

          l2 = []
          for c in command1:  # in Python, a string is just a sequence, so we can iterate over it! "setenv qnx_ifs_name 'ifs-rcar_h3.bin';"
            l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          l2_byte = bytearray(l2)
          print(l2_byte)
          ser.write(l2_byte)
          out = ser.read(1000000000)
          print(out)
          time.sleep(1)

          l2 = []
          for c in command2:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(1)

          l2 = []
          for c in command3:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          l2.append(10)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(5)

          l2 = []
          for c in command4:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(1)
          #
          l2 = []
          for c in command5:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          l2.append(10)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(8)
          #

          l2 = []
          for c in command6:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(10)
          #
          l2 = []
          for c in command7:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          l2.append(10)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(10)
          #
          l2 = []
          for c in command8:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          l2.append(10)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(10)

          l2 = []
          for c in command9:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(1)

          l2 = []
          for c in command10:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(1)


          l2 = []
          for c in command11:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(1)

          l2 = []
          for c in command12:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(1)


          l2 = []
          for c in command13:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          l2.append(10)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(5)


          l2 = []
          for c in command14:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(10)


          l2 = []
          for c in command15:  # in Python, a string is just a sequence, so we can iterate over it!
              l2.append(ord(c))
          l2.append(13)
          l2.append(10)
          print(l2)
          ser.write(l2)
          out = ser.read(1000000000)
          print(out)
          time.sleep(20)

  while ser.read():
    print('serial open')

  print('serial closed')
  ser.close()
except serial.serialutil.SerialException:
  print ('exception')


您可以将所有命令保存到一个列表中,并在列表中迭代,根据命令的类型,向
l2
数组添加额外的
\n
字符,并相应地管理睡眠时间。希望下面的代码有帮助-

try:
    ser = serial.Serial("COM32", baudrate=115200, timeout=0, stopbits=serial.STOPBITS_ONE)
    if ser.isOpen():
        print(ser.name + ' is open...')
    else:
        print(ser.name + ' is closed...')

    all_commands = [command1, command2, command3, command4, command5, command6, command7, command8,
                    command9, command10, command11, command12, command13, command14, command15]
    exit_commands = all_commands[:6]
    if 'exit' in exit_commands:
        ser.close()
        exit()
    else:
        sleep10_commands = all_commands[5:8] + all_commands[13:14]
        sleep5_commands = all_commands[2:3] + all_commands[12:13]
        sleep8_commands = all_commands[4:5]
        sleep20_commands = all_commands[14:15]
        extra_nw_line_commands = [all_commands[2], all_commands[4], all_commands[6], all_commands[7], all_commands[12]]
        for command in all_commands:
            l2 = [ord(c) for c in command]
            l2.extend([13, 10])
            if command in extra_nw_line_commands:
                l2.extend([10, 10])
            print(l2)
            l2_byte = bytearray(l2)
            print(l2_byte)
            ser.write(l2_byte)
            out = ser.read(1000000000)
            print(out)
            sleep_time = 1
            if command in sleep10_commands: sleep_time = 10
            elif command in sleep5_commands: sleep_time = 5
            elif command in sleep8_commands: sleep_time = 8
            elif command in sleep20_commands: sleep_time = 20
            time.sleep(sleep_time)

        while ser.read():
            print('serial open')

    print('serial closed')
    ser.close()
except serial.serialutil.SerialException:
    print ('exception')

首先,我有点困惑,为什么使用
ord
添加特征线并将字符串转换为bytearray

这里有几条建议:

  • 在一个列表中给出命令,这样您就可以对其进行迭代
  • 创建一个数据结构,如我的示例中的dict
    COMMANDS\u MAP
    ,以保留需要更长睡眠时间或更大填充空间的特殊命令的信息
  • 定义添加特征线填充的函数(定义为
    add_padding
  • 使用
    with
    语句打开连接,这将管理关闭连接。如果您没有使用Python3,可以在语句中关闭连接
  • 将幻数写成常量,例如
    端口
    读取大小
    波特率

为什么有些片段附加
'\r\n'
,而另一些片段附加
'\r\n\n'
?有什么不同?还有,你是否想过创建一个列表,列出你想要发送的所有“命令”?一个你可以循环的列表?听起来你的想法是对的。执行起来有困难吗?是的,我在执行中有一些困难!有些命令追加
'\r\n'
,而另一些命令追加
'\r\n\n'
,因为在某些命令中,我需要跳转更多行以使内容可见和清晰。关于命令列表,应该是这样的
commands=[“command1”、“command2”,…]command1=“setenv qnx_ifs_name'ifs-rcar_h3.bin”;”
创建一个函数,该函数具有不同调用的所有参数,如何?然后,您会在代码中得到一个函数调用列表,它应该和命令列表一样可读。一旦有了函数调用列表,您甚至可能会意识到进一步简化是可能的。
ord()
是Python中的一个函数,当参数是Unicode对象时,它返回一个整数,表示字符的Unicode代码点,或者当参数是8位字符串时字节的值,以便系统理解我的命令。@root Right,但是为什么不将特征线添加为字符串
/r/n
,并直接转换为bytearray而无需通过
ord
?因为系统不理解
/r/n
,您需要转换并发送AsciBut,您发送的是bytearray,所以不需要将它们转换为bytearray(“\r\n”,“utf8”)==bytearray([13,10])
import serial
import time

# Serial connection info
PORT = "COM32"
READ_SIZE = 1000000000
BAUDRATE = 115200
# Contains the padding and sleep in sec for commands
# default is 1 and 1s
COMMANDS_MAP = {
  "command3": {
    "padding": 3,
    "sleep": 5
  }
}

def add_padding(command, n=1):
  """
  Pad the given word with n breaklines.

  :param command: string to be padded
  :type command: string
  :param n: number of breaklines
  :type n: int
  :return: padded string with breaklines
  :rtype: string
  """
  return "{}\r".format(command).ljust(n, "\n")

def send_commands(commands):
  """
  Opens a serial connection and sends commands

  :param commands: list of commands to be sent
  :type commands: list of str
  """
  try:
    with serial.Serial(PORT, baudrate=BAUDRATE, timeout=0, stopbits=serial.STOPBITS_ONE) as ser:
      if ser.isOpen():
        print(ser.name + ' is open...')
      else:
        print(ser.name + ' is closed...')

      if "exit" in commands[:6]:
        return

      # Send commands
      for command in commands:
        c_info = COMMANDS_MAP.get(command)
        c_sleep, c_padding = c_info.get("sleep", 1), c_info.get("padding", 1)
        command_ready = bytearray(add_padding(command, c_padding), "utf8")
        ser.write(command_ready)
        out = ser.read(READ_SIZE)
        print(out)
        time.sleep(c_sleep)

      while ser.read():
        print('serial open')
    print('serial closed')
  except serial.serialutil.SerialException as e:
    print(e)

commands = ["command1", "command2", "command3"]
send_commands(commands)