2

I have a python code that reads output from command line:

import subprocess

def get_prg_output():
    p = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    return out

print get_prg_output()

In my office I want to simulate result in this mode:

def get_prg_output():
    return 'ok - program executed'

print get_prg_output()

Is there an elegant way to do this without comment out the original function?

I've try this:

import subprocess

debug = True

if not debug:
    def get_prg_output():
        p = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        out, err = p.communicate()
        return out
else:
    def get_prg_output():
        return 'ok - program executed'
print get_prg_output()

but I don't like it.

Thanks

1
  • 1
    What don't you like about your attempt? Commented Jan 22, 2013 at 18:13

3 Answers 3

4

I'd do something like this:

def _get_prg_output_real():
    p = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    return out

def _get_prg_output_fake():
    return 'ok - program executed'

Here you can toggle between:

get_prg_output = _get_prg_output_fake

or

get_prg_output = _get_prg_output_real

based on user input, or commandline arguments or config files or commenting/uncommenting a single line of code ...

Sign up to request clarification or add additional context in comments.

Comments

2
def get_prg_output_fake():
    return 'ok - program executed'

then, if you want to enable this simulation, just do

get_prg_output=get_prg_output_fake

1 Comment

It's a little freakish how we both posted simultaneously and named the fake function almost the same thing ...
0

I'd use an environment variable (or a command switch) to control it myself so you don't have to make code changes to test.

import os
import subprocess

def _get_prg_output_real():
    p = subprocess.Popen(['ls', '-l'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    out, err = p.communicate()
    return out

def _get_prg_output_fake():
    return 'ok - program executed'

if os.environ.get('DEBUG').lower() == 'true':
    get_prg_output = _get_prg_output_fake
else:
    get_prg_output = get_prg_output_real

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.