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

时间:2019-09-11 07:23:20

标签: python

此代码用于设置系统(我向系统发送命令以对其进行刷新,但首先我需要通过逐个命令发送命令来设置环境并从系统中读取输出以查看我是否发送了命令有很好的解释)。我需要优化它。

最优化代码的最佳方式是什么?我正在考虑添加一个包含所有命令的数组,然后将它们放入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')

2 个答案:

答案 0 :(得分:2)

首先,我有点困惑,为什么您使用ord添加换行符并将字符串转换为字节数组。

这里有一些建议:

  • 在列表中提供命令,以便您可以对其进行迭代。
  • 创建一个数据结构,例如我的示例中的字典COMMANDS_MAP,以保留需要较长睡眠或更大填充时间的特殊命令的信息。
  • 定义一个添加中断线填充的函数(将其定义为add_padding
  • 使用with语句打开连接,这将成功关闭连接。如果您不使用Python3,则可以在finally语句中关闭连接。
  • 将魔术数字写为常量,例如PORTREAD_SIZEBAUDRATE
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)

答案 1 :(得分:1)

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

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')