简体   繁体   中英

Python: Pass arguments from argparse to imported scripts

I'm building a command line tool which executes some python-scripts (k2_fig1 - k2_fig3) in one main *.py-file (let's call it "main_file.py"). In this "main_file.py" the user has to fill in some parameters for the database connection (username, dbname, etc.)
Now I don't know how to pass these parameters to every single python-script I am importing. What do I have to code to these imported files?
This is my code of the "main_file.py":

import argparse
def main():
  parser = argparse.ArgumentParser()

  parser.add_argument('-D', '--database', action="store", type=str, dest="my_dbname",  required=True, help="DB name")

  parser.add_argument('-U', '--username', action="store", type=str, dest="my_username", required=True, help="DB username")

  args = parser.parse_args()


  # Import different scripts
  import k2_fig1
  import k2_fig2
  import k2_fig3

if __name__ == '__main__':
  main()

Without knowing anything else about k2fig_1 et al., you'll need to call them using subprocess rather than importing them.

import argparse
import subprocess

def main():
  parser = argparse.ArgumentParser()
  parser.add_argument('-D', '--database', action="store", type=str, dest="my_dbname",  required=True, help="DB name")
  parser.add_argument('-U', '--username', action="store", type=str, dest="my_username", required=True, help="DB username")

  args = parser.parse_args()
  for script in ['k2_fig1', 'k2_fig2', 'k2_fig3']:
      subprocess.call([script, '-U', args.my_username, '-D', args.my_dbname])

if __name__ == '__main__':
  main()

I think the best way is to copy the namespace attributes to a "config" module::

import argparse

from . import config
from . import other

def update_obj(dst, src):
    for key, value in src.items():
        setattr(dst, key, value)

def main():
    parser = argparse.ArgumentParser()
    parser.add_argument('-D', '--database')
    parser.add_argument('-U', '--username')

    args = parser.parse_args('-D foo'.split())

    update_obj(config, args)

And the "other module"::

from . import config

def some_func():
    assert config.database == 'foo'

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM