标准输出到 dev/null 不适用于 python3.6 中的子进程模块

mal*_*har 3 python subprocess python-3.x python-3.6

使用Python 3.6.7Ubuntu 18.04.2 LTS

我试图通过 python 脚本调用 shell 脚本,并期望 stdout 为空,即我不想要控制台输出。

程序片段

def command_execution(self, cmd, cwd=None):
    """ Execute the command cmd without console output
    and return the exitcode
    """
    FNULL = open(os.devnull, 'w') # Method1
    self.log.debug("Executing command " +  cmd)
    exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True,  stdout=subprocess.DEVNULL)
    # Method1 call exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True,  stdout=FNULL)

    (_,_) = exec_cmd.communicate()
    exitcode = exec_cmd.returncode
    self.log.debug("Executed command {0} with exitcode {1}".format(cmd, exitcode))
    return exitcode
Run Code Online (Sandbox Code Playgroud)

正如上面提到的,我尝试了两种FNULL方法subprocess.DEVNULL。但是,我仍然在控制台上看到输出。

我在这里错过了什么吗?

Jos*_*osh 6

您是否有可能cmd输出到 stderr,而不是 stdout?

您可以通过执行以下操作进行测试:

exec_cmd = subprocess.Popen(cmd, cwd=cwd, shell=True,  stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
Run Code Online (Sandbox Code Playgroud)