# -*- coding: utf-8 -*-
# Created by wbb on 2022-04-13 14:10:07
import locale
import subprocess
import traceback
import logging
logger = logging.getLogger(__name__)
# noinspection PyBroadException
def execute(cmd) -> str:
"""
执行命令, 同步获取结果
"""
try:
locale_tuple = locale.getdefaultlocale()
encoding = "UTF-8"
if locale_tuple and locale_tuple[1]:
encoding = locale_tuple[1]
return subprocess.run(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, timeout=30).stdout.decode(encoding).strip()
except Exception:
logger.error("cmd: %s, err: %s" % (cmd, str(traceback.format_exc())))
return ""
# noinspection PyBroadException
def submit(cmd) -> subprocess.Popen:
"""
执行命令, 不需要等待结果
"""
try:
return subprocess.Popen(cmd, shell=True, stdout=subprocess.DEVNULL, stderr=subprocess.STDOUT, text=True)
except Exception:
logger.error("cmd: %s, err: %s" % (cmd, str(traceback.format_exc())))
# noinspection PyTypeChecker
return None
python执行系统命令
于 2022-07-28 16:50:34 首次发布