python执行shell命令

fun.py

import logging
from signal import SIGKILL
from subprocess import Popen, PIPE, STDOUT, TimeoutExpired, CalledProcessError
from time import sleep

import pexpect


def execute_shell_command(shell_command, timeout=None, check=False):
    """
    Execute a shell command and return STDOUT and STDERR in one combined result string.
    This function shall not raise any errors

    :param shell_command: command to execute
    :type shell_command: str
    :param timeout: kill process after timeout seconds
    :type: timeout: int, optional
    :param check: raise CalledProcessError if the return code is != 0
    :type: check: bool
    :return: str
    """
    output, return_code = execute_shell_command_get_return_code(shell_command, timeout=timeout)
    if check and return_code != 0:
        raise CalledProcessError(return_code, shell_command)
    return output


def execute_shell_command_get_return_code(shell_command, timeout=None):
    """
    Execute a shell command and return a tuple (program output, return code)
    Program output includes STDOUT and STDERR.
    This function shall not raise any errors

    :param shell_command: command to execute
    :type shell_command: str
    :param timeout: kill process after timeout seconds
    :type: timeout: int, optional
    :return: str, int
    """
    pl = Popen(shell_command, shell=True, stdout=PIPE, stderr=STDOUT)
    try:
        output = pl.communicate(timeout=timeout)[0].decode('utf-8', errors='replace')
        return_code = pl.returncode
    except TimeoutExpired:
        logging.warning("Execution timeout!")
        pl.kill()
        output = pl.communicate()[0].decode('utf-8', errors='replace')
        output += "\n\nERROR: execution timed out!"
        return_code = 1
    return output, return_code


def execute_interactive_shell_command(shell_command, timeout=60, inputs=None):
    """
    Execute an interactive shell command and return a tuple (program output, return code)
    This function shall not raise any errors

    :param shell_command: command to execute
    :type shell_command: str
    :param timeout: kill process after timeout seconds
    :type timeout: int
    :param inputs: dictionary {'EXPECTED_CONSOLE_OUTPUT': 'DESIRED_INPUT'}
    :type inputs: dict, optional
    :return: str, int
    """
    if inputs is None:
        inputs = {}
    trigger, inputs = _parse_inputs(inputs)
    output = b''
    child = pexpect.spawn(shell_command)
    while True:
        try:
            i = child.expect(trigger, timeout=timeout)
            sleep(0.1)
            child.sendline(inputs[i])
            output += child.before + child.after
        except pexpect.TIMEOUT:
            child.kill(SIGKILL)
            output += child.before
            output += b'\n\nError: Execution timed out!'
            break
        except pexpect.EOF:
            output += child.before
            break
    child.close()
    output = output.decode('utf-8', errors='ignore')
    return_code = child.exitstatus if child.exitstatus is not None else 1
    return output, return_code


def _parse_inputs(input_dict):
    trigger = []
    inputs = []
    for item in sorted(input_dict.keys()):
        trigger.append(item)
        inputs.append(input_dict[item])
    return trigger, inputs

execute.py

mount_rv = execute_shell_command('sudo mount {} -v -o ro,loop {} {}'.format(fs_type, file_path, mount_dir.name))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值