Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
236 views
in Technique[技术] by (71.8m points)

subprocess - Getting output from Python script in Python tests

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()

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

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)
''

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

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

Edit2: the documentation explains why

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...