subprocess.run
参数
check=True
- 自动跳出 subprocess.CalledProcessError 异常
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
| class RunCommand:
"""Run the command and check if the command is success
"""
def __init__(self, command: str, check=True, capture_output=True):
self.command = command
self.logger = logging.getLogger(self.__class__.__name__)
# self.logger = logging.getLogger(str(self.__class__))
self.success = True
self.returncode = None
self.check = check
self.capture_output = capture_output
def run(self) -> bool:
"""Run the command in the shell.
"""
try:
self.logger.info('try to run command: %s', self.command)
ret = subprocess.run(shlex.split(self.command),
check=self.check,
capture_output=self.capture_output
)
self.returncode = ret.returncode
except subprocess.CalledProcessError as e:
self.logger.info('Failed to call command: %s', self.command)
self.logger.exception(e)
self.success = False
return self.success
|
subprocess.Popen
- 与命令交互,可以取出命令输出内容
调用方式
with 方式
自动运行
1
2
3
4
5
6
7
| import subprocess
import shlex
file = 'test.pdf'
with subprocess.Popen(shlex.split(f"pdfinfo {file}"), stdout=subprocess.PIPE) as proc:
print(proc.stdout.read())
|
- subprocess.Popen.communicat() 手动运行
文章作者
上次更新
2022-04-26
(3050aaa)