在Python测试中从Python脚本获取输出 [英] Getting output from Python script in Python tests

查看:68
本文介绍了在Python测试中从Python脚本获取输出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在文件'bin/test'中有一个简单的python脚本:

I've got a simple python script in file '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运行它时,它会打印出所有内容:

When I run it with the --version param, or --help, it prints everything OK:

$ 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运行文件时,它什么也没得到:

When I run the file using subprocess.check_output, it doesn't get anything:

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

我正在使用带有Python版本的Ubuntu 11.10:

I'm using Ubuntu 11.10 with Python version:

python --version
Python 2.7.1+

我需要在测试中获取脚本输出.我该怎么办?

I need to get the script output in tests. How should I do that?

推荐答案

如果您使用的是shell=True,请不要将程序及其参数作为列表传递.这有效:

If you're using shell=True, don't pass the program and its arguments as a list. This works:

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

当然,将shell保留为False也可以.

of course, leaving shell as False would have worked too.

Edit2:文档说明了原因

the documentation explains why

在Unix上,使用 shell = True :如果 args 是字符串,则它指定 通过外壳执行的命令字符串.这意味着 字符串的格式必须与在 外壳提示.例如,这包括引号或反斜杠 转义带有空格的文件名.如果 args 是一个序列,则 第一项指定命令字符串,任何其他项将 被视为外壳本身的附加参数.

On Unix, with shell=True: If args is a string, it specifies the command string to execute through the shell. This means that the string must be formatted exactly as it would be when typed at the shell prompt. This includes, for example, quoting or backslash escaping filenames with spaces in them. If args is a sequence, the first item specifies the command string, and any additional items will be treated as additional arguments to the shell itself.

这篇关于在Python测试中从Python脚本获取输出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆