-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshell_os_popen.py
More file actions
59 lines (50 loc) · 2.6 KB
/
shell_os_popen.py
File metadata and controls
59 lines (50 loc) · 2.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
#!/usr/bin/env python3
# encoding: utf-8
# @author: hoojo
# @email: hoojo_@126.com
# @github: https://github.com/hooj0
# @create date: 2020-10-23
# @copyright by hoojo@2020
# @changelog python3 `shell -> os.popen` example
# ===============================================================================
# 标题:python3 call shell command os.popen example
# ===============================================================================
# 使用:利用python调用shell命令行
#
# os.popen(cmd, mode='r', buffering=-1)
# command – 使用的命令。
# mode – 模式权限可以是 ‘r’(默认) 或 ‘w’。
# bufsize – 指明了文件需要的缓冲大小:0意味着无缓冲;1意味着行缓冲;
# 其它正值表示使用参数大小的缓冲(大概值,以字节为单位)。
# 负的bufsize意味着使用系统的默认值,一般来说,对于tty设备,它是行缓冲;
# 对于其它文件,它是全缓冲。如果没有改参数,使用系统的默认值。
#
# 其返回值是shell指令运行后返回的状态码,int类型,
# 0表示shell指令成功执行,256表示未找到,
#
# 该方法以文件的形式返回shell指令运行后的结果,需要获取内容时可使用read()或readlines()方法
# -------------------------------------------------------------------------------
# 描述:该方法适用于shell命令需要输出内容的场景或读取参数输入的场景
# -------------------------------------------------------------------------------
import os
help(os.popen)
# -------------------------------------------------------------------------------
# 执行dir命令
# -------------------------------------------------------------------------------
output = os.popen('dir')
for line in output.readlines():
print(line[0:-1])
# output:
# -------------------------------------------------------------------------------
# 2020/10/23 周五 11:23 <DIR> .
# 2020/10/23 周五 11:23 <DIR> ..
# 2020/10/23 周五 11:23 1,809 shell_os_popen.py
# 2020/10/23 周五 11:21 2,351 shell_os_system.py
# 2020/10/23 周五 11:04 5,089 shell_subprocess.py
# 3 个文件 9,249 字节
# 2 个目录 20,369,559,552 可用字节
# -------------------------------------------------------------------------------
# 执行ipconfig命令
# -------------------------------------------------------------------------------
output = os.popen('ipconfig')
print(output.read()) # 读取输出所有内容