检查 os.system 响应中的字符串
Checking for string in os.system response
我正在 运行在 python 中执行以下命令以获取打印机状态的响应:
import os
printer_status = str(os.system('lpstat -p HP'))
当我 运行 这段代码时,无论我是否打印输出,它都会给我一个响应。它给出的响应示例是:
printer HP is idle. enabled since Mon 05 Jul 2021 15:17:02 BST
在python中有没有办法让我检查return结果中是否存在HP is idle这句话?因为我想看看打印机在发送下一个作业之前是否空闲。
更新
我已经试过了,但这不起作用。它 return 即使处于闲置状态也未闲置:
if "is idle." in printer_status:
print("Idle")
else:
print("Not Idle")
os.system()
will return the exit code of the command, not its output. What you are looking for is subprocess.check_output()
:
>>> import subprocess
>>> result = subprocess.check_output(["lpstat", "-p", "HP"])
>>> print(result)
b'printer HP is idle. enabled since Mon 05 Jul 2021 15:17:02 BST\n'
>>> b"is idle" in result
>>> True
尝试使用 subprocess
和正则表达式:
import subprocess, re
printer_status = subprocess.getoutput('lpstat -p HP')
is_printer_idle = len(re.findall("printer .* is idle", printer_status)) > 0
我正在 运行在 python 中执行以下命令以获取打印机状态的响应:
import os
printer_status = str(os.system('lpstat -p HP'))
当我 运行 这段代码时,无论我是否打印输出,它都会给我一个响应。它给出的响应示例是:
printer HP is idle. enabled since Mon 05 Jul 2021 15:17:02 BST
在python中有没有办法让我检查return结果中是否存在HP is idle这句话?因为我想看看打印机在发送下一个作业之前是否空闲。
更新
我已经试过了,但这不起作用。它 return 即使处于闲置状态也未闲置:
if "is idle." in printer_status:
print("Idle")
else:
print("Not Idle")
os.system()
will return the exit code of the command, not its output. What you are looking for is subprocess.check_output()
:
>>> import subprocess
>>> result = subprocess.check_output(["lpstat", "-p", "HP"])
>>> print(result)
b'printer HP is idle. enabled since Mon 05 Jul 2021 15:17:02 BST\n'
>>> b"is idle" in result
>>> True
尝试使用 subprocess
和正则表达式:
import subprocess, re
printer_status = subprocess.getoutput('lpstat -p HP')
is_printer_idle = len(re.findall("printer .* is idle", printer_status)) > 0