【问题标题】:How to access arguments on an imported flask script which uses argparse?如何访问使用 argparse 的导入烧瓶脚本的参数?
【发布时间】:2023-10-08 20:05:01
【问题描述】:

我有一个 python 脚本说 A,它有一些使用 argparse 在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)

我已经编写了另一个 python 脚本 B,它使用 flask 在 localhost 上运行 Web 应用程序。

我正在尝试将 B 中的脚本 A 导入为:

from <folder> import A

如何在 A 中提供运行脚本 B 所需的参数? 我想通过主烧瓶 python 脚本(即脚本 B)传递参数来在脚本 B 中运行 A。

我想使用 A 的所有功能,但我不想更改 A 的结构或将相同的代码复制粘贴到 B 中。

我一直在尝试类似的东西:

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

但这似乎不起作用。我从this SO 答案中获得灵感,但我想我错过了一些东西。

有人知道如何有效地做到这一点吗?

【问题讨论】:

    标签: python flask python-import argparse args


    【解决方案1】:

    linked 的答案帮助我使它适用于我的代码。很简单,有效使用 kwargs 可以帮助解决这个问题。

    .
    .
    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)
    

    对于烧瓶脚本,只需使用,

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

    除了在使用 main 函数时声明所有默认参数之外,我没有找到任何其他方法。

    【讨论】: