【问题标题】:Using if statement when examining results from command line从命令行检查结果时使用 if 语句
【发布时间】:2019-01-27 16:04:19
【问题描述】:

我正在尝试为名为 windscribe-cli 的 VPN 程序编写 GUI。我需要区分VPN是否连接。
Windscribe 状态的结果如下所示:

windscribe -- pid: 1479, status: running, uptime: 1h 50m, %cpu: 0.0, %mem: 0.4 IP: 143.159.73.130 已断开

DISCONNECTED 用红色写。

对于用彩色书写的单词,我无法从 if 或 elif 中得到结果。

我尝试过使用 if elif,但他们忽略了彩色书写。 使用 print word_list[14] 以颜色输出单词。

import sh

def status():

    status = ""
    windscribe_status = sh.windscribe("status")
    word_list = windscribe_status.split()

    if word_list[14] == "CONNECTED":
        status = "connected"
    elif word_list[14] == "DISCONNECTED":
        status = "disconnected"

    return status

print status()

我希望看到连接或断开连接,但什么也看不到。

【问题讨论】:

  • 嗨,詹姆斯,您的代码无法按预期工作,因为有额外的“特殊符号”可以使输出更加丰富多彩。在测试之前,您必须删除或忽略这些符号。使用正则表达式或子字符串会有所帮助。更多关于 ansi 序列的信息:en.m.wikipedia.org/wiki/ANSI_escape_code
  • word_list 中的实际内容是什么?可以打印吗?
  • 你可以简单地测试if 'DISCONNECTED' in windscribe_status:
  • 哇,哪个垃圾程序不检查输出是通过管道传输还是转到 tty?

标签: python shell python-2.x string-comparison


【解决方案1】:

如果我是你,我不会围绕颜色构建这个。 windscribe 可能是一个例外(这种情况并不少见),但 cli 程序通常会在写出终端转义符以更改颜色之前检查其输出是否为终端设备。 this blog post 是用 python 编写的 writing 彩色数据到终端的示例,但应该很好地了解颜色代码背后的机制以及为什么你的单词与你期望的不匹配。所以可能最好忽略颜色。

坦率地说,使用状态消息也不是很理想。随着时间的推移,这些用于人类消费的状态通常无法提供足够一致的行为来提供非常可靠的界面。许多程序将以对程序更友好的方式公开它们的状态 - 可能是您可以从中读取状态的套接字、文件或 cli 程序的不同调用。但也许不是 - 取决于程序。通常,开源程序包含这些功能,因为它们的开发人员通常在 CLI 编程领域经验丰富 - 专有代码,较少。但是ymmv。

不管怎样,你的问题是这样的:

word_list = windscribe_status.split()

这将在空格上拆分,但不会排除彩色输出周围的颜色代码。实际上,您可以通过执行以下操作使您的程序在面对不断变化的状态消息时更加健壮,也更加简单:

if "disconnected" in winscribe_status.lower():
   handle disconnected
elif "connected" in winscribe_status.lower():
   handle connected

在这里,我使用in 来检查子字符串;并且我使用lower() 将自己与未来的大小写更改隔离开来(并非绝对必要,但如果大小写发生更改,我会觉得这样做是值得的)。

以下是删除了您的详细信息的完整过程示例:

import subprocess
test_inputs = [
  "I AM DISConnected!",
  "\033[1;31mDISCONNECTED\033[0m",
  "Successfully \033[1;32mConnected\033[0m"
]
for cmd in test_inputs:
  res = subprocess.check_output(["echo",'-n',cmd])
  res = str(res)
  print("Message was: '{}'".format(res))
  if 'disconnected' in res.lower():
    print('Disconnected!')
  elif 'connected' in res.lower():
    print('Connected!')

我是这样跑的。 Pyhton3 输出看起来有点不同,但逻辑仍然有效。

$ python ./t.py
Message was: 'I AM DISConnected!'
Disconnected!
Message was: 'DISCONNECTED'
Disconnected!
Message was: 'Successfully Connected'
Connected!

在这里,单词的顺序无关紧要,它们的数量或大小写也不重要,它可以使用或不使用颜色,它只是忽略。顺序很重要;显然,“已连接”将匹配“已断开”匹配的任何地方。

【讨论】:

  • 这正是我想要的。谢谢。
猜你喜欢
  • 2015-04-22
  • 2015-06-24
  • 1970-01-01
  • 2016-12-14
  • 1970-01-01
  • 2017-04-21
  • 2016-07-22
  • 2021-01-02
相关资源
最近更新 更多