Python获取CMD命令行输出结果
admin
2021-02-03 22:32:39
0

一,os.system()

这种方式虽然可以在控制台看到回显的结果,但是却无法接收到这些内容,更无法对结果进行处理

官方文档对返回结果说明如下在Windows上,返回值是运行命令后系统外壳程序返回的值。…通常是cmd.exe,它返回命令运行的退出状态;

即os.system()返回值是命令执行后退出的状态,正常为0,异常为1

正常情况In[5]: os.system(“dir”) Volume in drive F is 数据 Volume Serial Number is 0006-F904 Directory of F:\Practice\PycharmProjects\PythonBasic 2019/04/29 10:17

. 2019/04/29 10:17

.. 2019/04/29 11:45

.idea 2019/03/31 21:36

venv 2019/03/31 21:35

_01_HelloWorld 2019/03/31 21:36

_02_数据类型 …(略) 0 File(s) 0 bytes 15 Dir(s) 41,743,155,200 bytes free Out[5]: 0

注意末尾的Out [5]:0,这才是真正的返回值

异常情况In[6]: os.system(“directory”) ‘directory’ is not recognized as an internal or external command, operable program or batch file. Out[6]: 1

Out [6]:1,表示执行出现异常二,os.popen()

具体用法如下:result = os.popen(‘ipconfig’) # 返回的结果是一个

对象,需要读取后才能处理 context = result.read() for line in context.splitlines(): print(line) result.close()

os.popen()的返回值是一个类_wrap_close,需要重定向read()之后才能得到一个str

官方文档对返回值说明:打开到命令cmd或来自命令cmd的管道。返回值是连接到管道的打开文件对象,可以根据模式是“ r”(默认)还是“ w” 来进行读取或写入。

相关内容