【python2】commands模块getstatusoutput函数的小问题
admin
2023-07-12 04:03:38
0

[TOC]

问题

import commands as subprocess
status, _ = subprocess.getstatusoutput("ps -elf|grep fuckU")
# status:
# 255
  • 这里的status按照grep的定义其实应该返回1,也就是没有grep到匹配项,在shell中echo $? 结果为1
    但是python2getstatusoutput获取的并不是os.exitcode()而是os.wait()的返回值。

  • python3由于使用的是subprocess = modified(commands + subprocess),同样执行
    status, _ = subprocess.getstatusoutput("ps -elf|grep fuckU")

    得到的status为正确的1

我是怎么解决这个问题

兼顾Python2和Python3的使用习惯,使用google开源的subprocess32代替commands

什么是subprocess32

谷歌将Python32的subprocess移植到了python2版本中。据说这是线程安全的版本。
最新的Python32版本为3.5.3也就是将python3.5.3中的subprocess基本功能移植到了Python2中。但是subprocess32不包含原本commands中的函数。

Timeout support backported from Python 3.3 is included.
The run() API from Python 3.5 was backported in subprocess32 3.5.0.
Otherwise features are frozen at the 3.2 level.

这里我们使用subprocess32.run()方法去模拟getstatusoutput等便捷的函数(python3官方实现)

# 原本的timeout=None,因为Python2不支持*args,**kwargs外再有kwargs,暂时移出参数项,放至函数体内
# def check_output(*popenargs, timeout=None, **kwargs):
def check_output(*popenargs, **kwargs):
    r"""Run command with arguments and return its output.

    If the exit code was non-zero it raises a CalledProcessError.  The
    CalledProcessError object will have the return code in the returncode
    attribute and output in the output attribute.

    The arguments are the same as for the Popen constructor.  Example:

    >>> check_output(["ls", "-l", "/dev/null"])
    b'crw-rw-rw- 1 root root 1, 3 Oct 18  2007 /dev/null\n'

    The stdout argument is not allowed as it is used internally.
    To capture standard error in the result, use stderr=STDOUT.

    >>> check_output(["/bin/sh", "-c",
    ...               "ls -l non_existent_file ; exit 0"],
    ...              stderr=STDOUT)
    b'ls: non_existent_file: No such file or directory\n'

    There is an additional optional argument, "input", allowing you to
    pass a string to the subprocess's stdin.  If you use this argument
    you may not also use the Popen constructor's "stdin" argument, as
    it too will be used internally.  Example:

    >>> check_output(["sed", "-e", "s/foo/bar/"],
    ...              input=b"when in the course of fooman events\n")
    b'when in the course of barman events\n'

    If universal_newlines=True is passed, the "input" argument must be a
    string and the return value will be a string rather than bytes.
    """
    timeout = None
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')

    if 'input' in kwargs and kwargs['input'] is None:
        # Explicitly passing input=None was previously equivalent to passing an
        # empty string. That is maintained here for backwards compatibility.
        kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''

    return subprocess.run(*popenargs, stdout=subprocess.PIPE, timeout=timeout, check=True,
                          **kwargs).stdout

def getstatusoutput(cmd):
    """Return (exitcode, output) of executing cmd in a shell.

    Execute the string 'cmd' in a shell with 'check_output' and
    return a 2-tuple (status, output). The locale encoding is used
    to decode the output and process newlines.

    A trailing newline is stripped from the output.
    The exit status for the command can be interpreted
    according to the rules for the function 'wait'. Example:

    >>> import subprocess
    >>> subprocess.getstatusoutput('ls /bin/ls')
    (0, '/bin/ls')
    >>> subprocess.getstatusoutput('cat /bin/junk')
    (1, 'cat: /bin/junk: No such file or directory')
    >>> subprocess.getstatusoutput('/bin/junk')
    (127, 'sh: /bin/junk: not found')
    >>> subprocess.getstatusoutput('/bin/kill $$')
    (-15, '')
    """
    try:
        data = check_output(cmd, shell=True, universal_newlines=True, stderr=subprocess.STDOUT)
        exitcode = 0
    except subprocess.CalledProcessError as ex:
        data = ex.output
        exitcode = ex.returncode
    if data[-1:] == '\n':
        data = data[:-1]
    return exitcode, data

def getoutput(cmd):
    """Return output (stdout or stderr) of executing cmd in a shell.

    Like getstatusoutput(), except the exit status is ignored and the return
    value is a string containing the command's output.  Example:

    >>> import subprocess
    >>> subprocess.getoutput('ls /bin/ls')
    '/bin/ls'
    """
    return getstatusoutput(cmd)[1]

题外话

其实python官方推荐使用这个函数执行系统命令
subprocess.run()

但是这个函数将输出直接print到终端中

如果需要屏蔽恣意的屏幕输出,可以使用subprocess.DEVNULL (subprocess 3.5.3中有)

# 即
x = subprocess.run('echo 250', shell=True, stderr=subprocess.DEVNULL, stdout=subprocess.DEVNULL)
# x:
# CompletedProcess(args='echo 250', returncode=0)

# reference: https://stackoverflow.com/questions/8529390/is-there-a-quiet-version-of-subprocess-call

相关内容

热门资讯

OpenAI,正式组建机器人事... 人工智能(AI)领域巨头OpenAI发布公告,宣布大力扩张内部机器人事业部,正式全面切入硬件赛道,实...
星火空间完成近亿元Pre-A轮... 据星火空间消息,6月1日,合肥星火空间科技有限公司完成近亿元Pre-A轮融资。本轮融资由云泽资本和轨...
刚刚,宇树IPO闪电过会!王兴... 智东西 作者 | 许丽思 编辑 | 漠影 智东西6月1日报道,刚刚,宇树通过上交所上市委会议审议。 ...
京东工业发起百川计划 携手上游... 京东工业大模型生态发布会6月1日在北京举行,京东工业携手合作伙伴正式开启“百川计划”,从数据、模型、...
强脑科技预计今年机械手销量大涨... IT之家 6 月 2 日消息,据彭博社 2 日(今天)报道,强脑科技预计,随着中国人形机器人产业快速...
一图看懂差距!iPhone 1... 快科技6月2日消息,iPhone 18 Pro不同版本电池容量不同的相关话题冲上社交平台热搜榜,引发...
iPhone 18 Pro 或... 据科技狐,近日,知名爆料人 Sonny Dickson 分享了 iPhone 18 Pro 全套机模...
武契奇:不排除卸任总统后担任总... 塞尔维亚总统武契奇近期密集释放政坛人事与大选相关信号,明确无意在 2027 年总统任期届满后谋求连任...
6月新机夯到拉盘点,告诉你哪台... 现在这形势,手机升价是不可能躲得过的了,而且涨价期至少持续两年。那既然内存涨价躲不过,就只能选升级大...
伊朗公开已故最高领袖哈梅内伊安... 新华社德黑兰6月2日电 据伊朗伊斯兰共和国通讯社2日报道,根据伊朗已故最高领袖阿里·哈梅内伊生前遗愿...