从命令提示符获取文本

时间:2020-08-27 15:28:42

标签: python command-line python-3.6 command-prompt

我想从cmd提示结果中获取文本。 例如,

import os
os.system('net view')

以上几行给我以下几行

Server Name            Remark

-------------------------------------------------------------------------------
\\LAPTOP-5VBGN416
\\RASPBERRYPI          Samba 4.9.5-Debian
The command completed successfully

我的目标是检查是否存在RASPBERRYPI变量。我该怎么办?

1 个答案:

答案 0 :(得分:2)

尝试一下:

import os
output = os.popen('net view').read()

if 'RASPBERRYPI' in output:
    print("'RASPBERRYPI' was found.")
else:
    print("'RASPBERRYPI' was NOT found.")

注意:有些人声称os.popen()已过时,但根据https://raspberrypi.stackexchange.com/questions/71547/is-there-a-problem-with-using-deprecated-os-popenos.popen()在Python 2.6中已过时,但在{2.6 Python 3.x,因为在3.x中是使用subprocess.Popen()实现的。


如果您更喜欢使用subprocess包,则可以通过以下方式捕获输出:

import subprocess
output = subprocess.Popen("net view",   # your command
                          shell=True,
                          stdout=subprocess.PIPE,
                          stderr=subprocess.PIPE
         ).communicate()[0]

(如果愿意,您可以将.Popen()的前两个参数分别更改为["net", "view"]shell=False,但是我有这样做的理由留给读者进行研究。);-)

相关问题