Search code examples
pythonflaskpython-importargparseargs

How to access arguments on an imported flask script which uses argparse?


I have a python script say A which has some arguments specified using argparse in main.

.
.
def main(args):
  # use the arguments
.
.

if __name__ == '__main__':
  parser = argparse.ArgumentParser(..)
  parser.add_argument(
        '-c',
        '--classpath',
        type=str,
        help='directory with list of classes',
        required=True)
  # some more arguments
  args = parser.parse_args()

  main(args)

I've written another python script say B, which uses flask to run a web-application on localhost.

I'm trying to import the script A in B as:

from <folder> import A

How do I give in the arguments that are required in A for running script B? I want to run A inside script B by passing parameters via the main flask python script (viz., the script B).

I want to use all the functionality of A, but I'd rather not change the structure of A or copy-paste the same exact code inside B.

I've been trying something like:

@app.route(...)
def upload_file():
    A.main(classpath = 'uploads/')

but that doesn't seem to work. I'm taking inspiration from this SO answer, but I guess I'm missing something.

Does anybody have some idea on how to do this efficiently?


Solution

  • The answer which I've linked helped me to made it work for my code. Quite simply, efficient use of kwargs can help solve it.

    .
    .
    def main(**kwargs):
      file_path_audio = kwargs['classpath']
      # use the other arguments
    .
    .
    
    if __name__ == '__main__':
      parser = argparse.ArgumentParser(..)
      parser.add_argument(
            '-c',
            '--classpath',
            type=str,
            help='directory with list of classes',
            required=True)
      # some more arguments
      kwargs = parser.parse_args()
    
      main(**kwargs)
    

    And for the flask script, simply use,

    @app.route(...)
    def upload_file():
        A.main(classpath = 'uploads/', ..) # have to add all the arguments with their defaults
    

    I haven't found any other way than to state all the default arguments while using the main function.