How to set argparse arguments from python script
<p>I have a <code>main</code> function specified as entry point in my package's <code>setup.py</code> which uses the <code>argparse</code> package in order to pass command line arguments (see <a href="http://stackoverflow.com/questions/2853088/setuptools-not-passing-arguments-for-entry-points">discussion here</a>):</p>

<pre><code># file with main routine specified as entry point in setup.py
import argparse
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('a', type=str, help='mandatory argument a')
    args = parser.parse_args()
</code></pre>

<p>Ideally, I would like to use the same <code>main</code> function in the package's tests as suggested <a href="http://python-packaging.readthedocs.io/en/latest/command-line-scripts.html" rel="nofollow">here</a>. In the latter context, I would like to call the <code>main</code> function from within the test class and set (some of) the command line arguments prior to the function call (which otherwise will fail, due to missing arguments).</p>

<pre><code># file in the tests folder calling the above main function
class TestConsole(TestCase):
    def test_basic(self):
        set_value_of_a()
        main()
</code></pre>

<p>Is that possible?</p>

<p>The <strong>argparse</strong> module actually reads input variables from special variable, which is called <strong>ARGV</strong> (short from <strong>ARG</strong>ument <strong>V</strong>ector). This variable is usually accessed by reading <strong>sys.argv</strong> from <strong>sys</strong> module.</p>

<p>This variable is a ordinary list, so you can append your command-line parameters to it like this:</p>

<pre><code>import sys
sys.argv.extend(['-a', SOME_VALUE])
main()
</code></pre>

<p>However, messing with sys.argv at runtime is not a good way of testing. 
A much more cleaner way to replace the <strong>sys.argv</strong> for some limited scope is using <strong>unittest.mock.patch</strong> context manager, like this:</p>

<pre><code>with unittest.mock.patch('sys.argv'. ['-a', SOME_VALUE]):
    main()
</code></pre>

<p><a href="https://docs.python.org/3/library/unittest.mock.html#unittest.mock.patch" rel="nofollow" title="Read more about unittest.mock.patch in docmentation">Read more about unittest.mock.patch in documentation</a></p>

<p>Also, check this SO question:</p>

<p><a href="http://stackoverflow.com/questions/18668947/how-do-i-set-sys-argv-so-i-can-unit-test-it">How do I set sys.argv so I can unit test it?</a></p>

python argparse setup.py entry-point