在下面的protobuf代码中,len(sys.argv)!= 2做什么?

时间:2019-06-18 08:50:36

标签: python protocol-buffers

我是协议缓冲区的新手,目前正在研究它。我在Google的protobuf开发人员教程中查看了该教程。我找到了将数据写入协议缓冲区的python程序。在这里,我不明白这条线是做什么的。另外要运行此命令,我必须在cmd上传递任何参数。(Windows)

    if len(sys.argv) != 2:
      print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
      sys.exit(-1)

下面是下面的代码,用于写入数据。

def PromptForAddress(person):
  person.id = int(raw_input("Enter person ID number: "))
  person.name = raw_input("Enter name: ")

  email = raw_input("Enter email address (blank for none): ")
  if email != "":
    person.email = email

  while True:
    number = raw_input("Enter a phone number (or leave blank to finish): ")
    if number == "":
      break

    phone_number = person.phones.add()
    phone_number.number = number

    type = raw_input("Is this a mobile, home, or work phone? ")
    if type == "mobile":
      phone_number.type = addressbook_pb2.Person.MOBILE
    elif type == "home":
      phone_number.type = addressbook_pb2.Person.HOME
    elif type == "work":
      phone_number.type = addressbook_pb2.Person.WORK
    else:
      print "Unknown phone type; leaving as default value."


if len(sys.argv) != 2:
      print "Usage:", sys.argv[0], "ADDRESS_BOOK_FILE"
      sys.exit(-1)
address_book = addressbook_pb2.AddressBook()

# Read the existing address book.
try:
  f = open(sys.argv[1], "rb")
  address_book.ParseFromString(f.read())
  f.close()
except IOError:
  print sys.argv[1] + ": Could not open file.  Creating a new one."

# Add an address.
PromptForAddress(address_book.people.add())

# Write the new address book back to disk.
f = open(sys.argv[1], "wb")
f.write(address_book.SerializeToString())
f.close()

1 个答案:

答案 0 :(得分:1)

这部分正在检查提供的参数数量。如果缺少某些内容,则该程序存在错误。可以在here中找到更多详细信息。

我建议切换到专用框架(例如click)来处理CLI(命令行界面)的构建。