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
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 ...
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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.