Reputation: 53
folks, i inherited a python script main using optParse to construct a menu of items for the user to pick through:
def main():
parser = optParse(prog='script')
#parser.add_option("-e","--repeat",dest="repeat",type=int,default=3,help="Total number of times to do the checking.")
parser.add_option("-H","--time",dest="time", type='float', default=1.0,help="Time in hours to run the test.")
what need to do is to call this main function from within a running python session, but don't quite know how to specify the parameters. something similar to this:
import script
script.main(['-e', '5', '-H', '2'])
however, the main function has no input parameters as it is. What is the easiest way to modify main to accomplish passing parameters in the manner specified?
Upvotes: 0
Views: 180
Reputation: 231655
Your parser needs a parse_args
call, which from the docs looks like:
(options, args) = parser.parse_args(args=None, values=None)
args
can be a list of strings. If it is None
, it will use sys.argv[1:]
.
Sometimes the main is defined as
def main(argv=None):
parser = ...
...
options, args = parser.parse_args(argv)
Then the main caller can either use
main() # or
main(['-e','5'...])
Upvotes: 1
Reputation: 53
from the answer from Tim Roberts, the following works:
def main():
parser = optParse(prog='script')
#parser.add_option("-e","--repeat",dest="repeat",type=int,default=3,help="Total number of times to do the checking.")
parser.add_option("-H","--time",dest="time", type='float', default=1.0,help="Time in hours to run the test.")
sys.argv = ['scripyt.py', '-e', '5', '-H', '2']
then just calling the following from the running python session:
script.main()
Upvotes: 0