Python如何实现shell命令的执行

本文介绍了在Python中执行Shell命令的四种方法,包括直接执行、通过返回码判断、使用communicate()获取输出以及利用commands包获取状态和输出,适用于不同场景下的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方式一:最直接的执行方式,但是页面上打印的命令执行结果 0或者1,有事不能满足需求

import os 
os.sys(cmd)

方式二:可以通过返回的process.returncode 属性是否等于0来判断其命令是否正常执行完毕,返回的为process对象,参照方式三,可以通过process.communicate()来获得其标准输出以及执行错误的输出

    def __exec_cmd(self, command, timeout=None):
        """
        执行cmd的同时,会定期检测是否正常执行,且是否正常执行完毕
        """
        start = datetime.datetime.now()
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        while process.poll() is None:
            time.sleep(0.1)
            now = datetime.datetime.now()
            if timeout is not None and (now - start).seconds > timeout:
                os.kill(process.pid, signal.SIGKILL)
                os.waitpid(-1, os.WNOHANG)
                pipout = '\n'.join([s.read() for s in [process.stdout, process.stderr] if s is not None])
                self.logger.warn("Executing [%s] TIMOUT, killed the process" % command)
        
        if process is not None and process.returncode != 0:
            self.logger.info("Executing [%s]" % command)
            out, err = process.communicate()
            pipout = ' '.join([out, err])
            self.logger.error("[retcode %d] %s" % (process.returncode, pipout))

        return process

方式三:

def run_cmd(cmd, verbose=False):  # 执行cmd并返回标准输出
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=True)
    out, error = p.communicate()
    logging.info('run cmd: %s' % cmd)
    if verbose:
        logging.info('out is %s' % out)
        logging.info('error is %s' % error)
    return out.decode('utf-8')

方式四:通过commands包可以获得返回值和输出

import commands
(status, output) = commands.getstatusoutput('cat /proc/cpuinfo')
print status, output
>>> import commands
>>> commands.getstatusoutput('ls /bin/ls')
(0, '/bin/ls')
>>> commands.getstatusoutput('cat /bin/junk')
(256, 'cat: /bin/junk: No such file or directory')
>>> commands.getstatusoutput('/bin/junk')
(256, 'sh: /bin/junk: not found')
>>> commands.getoutput('ls /bin/ls')
'/bin/ls'
>>> commands.getstatus('/bin/ls')
'-rwxr-xr-x 1 root 13352 Oct 14 1994 /bin/ls'

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值