在Python测试中获取Python脚本的输出

0 投票
1 回答
2072 浏览
提问于 2025-04-17 12:06

我有一个简单的Python脚本,文件名是 'bin/test':

#!/usr/bin/env python

import argparse

PROGRAM_NAME        = "name"
PROGRAM_VERSION     = "0.0.1"
PROGRAM_DESCRIPTION = "desc"
parser = argparse.ArgumentParser(prog=PROGRAM_NAME, description=PROGRAM_DESCRIPTION)
parser.add_argument('--version', action='version', version='%(prog)s ' + PROGRAM_VERSION)

args = parser.parse_args()

当我用 --version 参数或者 --help 参数运行它时,它会正常输出所有内容:

$ bin/test --version
name 0.0.1

$ bin/test --help
usage: name [-h] [--version]

desc

optional arguments:
  -h, --help  show this help message and exit
  --version   show program's version number and exit

但是当我用 subprocess.check_output 来运行这个文件时,它什么都没有输出:

>>> subprocess.check_output(["bin/test", "--help"],  stderr=subprocess.STDOUT, shell=True)
''
>>> subprocess.check_output(["bin/test", "--version"],  stderr=subprocess.STDOUT, shell=True)
''

我使用的是Ubuntu 11.10,Python的版本是:

python --version
Python 2.7.1+

我需要在测试中获取这个脚本的输出。我该怎么做呢?

1 个回答

5

如果你使用 shell=True,那么就不要把程序和它的参数作为一个列表传递。这样做是可以的:

subprocess.check_output("bin/test --help",  stderr=subprocess.STDOUT, shell=True)

补充:当然,把 shell 设置为 False 也可以正常工作。

补充2:文档里有解释原因。

在Unix系统中,当 shell=True 时:如果 args 是一个字符串,它就指定了要通过shell执行的命令字符串。这意味着这个字符串必须和你在shell提示符下输入时的格式完全一样。例如,如果文件名中有空格,你需要用引号或反斜杠来转义它们。如果 args 是一个序列(比如列表),第一个项目指定了命令字符串,后面的项目会被当作额外的参数传递给shell本身。

撰写回答