title: pytest - command line argument outside test function
body: <p>How to pass command line option as variable to my pytest non test file e.g. database name.</p>
  
  <p>When i try:</p>
  
  <pre class="lang-py prettyprint-override"><code>import sys
  import getopt
  
  
  """argv = sys.argv[1:]
  
  opts, args = getopt.getopt(argv, "e:")
  
  for opt, arg in opts:
      if opt in ['-e']:
          if arg == "test1":
              base_url = "url-test1.com"
              db_name = "db_test1"
          elif arg == 'test2':
              base_url = "url-test2.com"
              db_name = "db_test2"
          elif arg == 'test3':
              base_url = "url-test3.com"
              db_name = "db_test3"
      return base_url
  </code></pre>
  
  <p>and run</p>
  
  <pre><code> python -m pytest -e test1
  </code></pre>
  
  <p>looks like pytest can't get -e flag</p>
  
  <p>ERROR: usage: <strong>main</strong>.py [options] [file_or_dir] [file_or_dir] [...]</p>
  
  <p><strong>main</strong>.py: error: unrecognized arguments: -e</p>
  
  <p>inifile: None</p>
  
  <p>I also try pytest addoption and passing variable to test files works fine but how to pass cmnd line option as value to non test file?</p>
  
  <pre class="lang-py prettyprint-override"><code>def pytest_addoption(parser):
      parser.addoption("--url", action="store", default="url-test1.com")
      parser.addoption("--db", action="store", default="test1")
  
  @pytest.fixture()
  def url(request):
      return request.config.getoption("--url")
  
  def db_name(request):
      return request.config.getoption("--db") #I want to pass this value to mysql.connector as database=db_name
  </code></pre>
  
  <p><strong>EDIT 1</strong></p>
  
  <p>so my db_connect.py lokks like that</p>
  
  <pre><code>import mysql.connector
  import argparse
  
  
  def parse_args():
      parser = argparse.ArgumentParser()
      parser.add_argument('--db', required=True, type=str, help="Your database name")
      return parser.parse_args()
  
  
  def main():
      args = parse_args()
      db = args.db
      return db
  
  
  mydb = mysql.connector.connect(
      user='username',
      password='password',
      host='host',
      database=main()
  )
  
  
  if __name__ == '__main__':
      main()
  
  </code></pre>
  
  <p>and when i try to run</p>
  
  <pre><code>py.test --db test1
  </code></pre>
  
  <p>I got this error</p>
  
  <pre><code>ERROR: usage: py.test [options] [file_or_dir] [file_or_dir] [...]
  py.test: error: unrecognized arguments: --db
    inifile: None
  </code></pre>
  
  <p>but when i run</p>
  
  <pre><code>py.test
  </code></pre>
  
  <p>i got </p>
  
  <pre><code>usage: py.test [-h] --db DB
  py.test: error: the following arguments are required: --db
  </code></pre>
  
  <p>argument is required but when i pass it is unrecognized. How to handle it?</p>