Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass command line arguments from one python module to another

Tags:

python

I am writing a unittest for a module that accepts command line arguments. I've used optparse in the module to accept the args.

So when I execute the module directly I just type:-

module.py -e 42 -g 84

So far in my unittest I simply create an instance of the module to test then call a specific method:-

instance = module.className()
instance.method()

Can someone please tell me how to pass the command line args to module.py from another module such as a unittest?

Do I use optparse in my unittest and somehow incorporate in when generating the instance of module.py?

Thanks in advance.

like image 687
user788462 Avatar asked Apr 12 '12 22:04

user788462


People also ask

How do you give a Python script a command line input?

If so, you'll need to use the input() command. The input() command allows you to require a user to enter a string or number while a program is running. The input() method replaced the old raw_input() method that existed in Python v2. Open a terminal and run the python command to access Python.

What module is used for command line arguments in Python?

Python provides a getopt module that helps you parse command-line options and arguments. sys. argv is the list of command-line arguments.


2 Answers

You just have to modify the list sys.argv which represents the list of command line arguments. This list is global to the python interpreter so you don't have to pass it around.

import sys
from optparse import OptionParser

parser = OptionParser()
parser.add_option("-e")
parser.add_option("-g")

print sys.argv # unmodified
(options, args) = parser.parse_args()
print (options, args)

sys.argv = ['module.py','-e','42','-g','84'] # define your commandline arguments here

(options, args) = parser.parse_args()
print (options, args)

Note: The OptionParser Module is deprecated so if possible switch to argparse (see: http://docs.python.org/library/argparse.html#module-argparse). All you need is Python 2.7.

like image 127
mash Avatar answered Nov 14 '22 21:11

mash


Three alternatives:

1) Use some shell, instead of fixating on 100% Python.

2) Pass around sys.argv (and perhaps a workalike vector) as needed

3) Call the functions that your command line option dispatcher calls instead

like image 39
user1277476 Avatar answered Nov 14 '22 22:11

user1277476