【问题标题】:Python import function from another file via argparsePython 通过 argparse 从另一个文件导入函数
【发布时间】:2023-01-24 23:29:52
【问题描述】:

我正在编写一个小的实用函数,它接受 Python 文件位置的输入参数,以及一个在 Python 文件中调用的函数

例如src/path/to/file_a.py

def foo():
  ...

在效用函数中,我像这样解析参数:

python ./util.py --path src/path/to/file_a.py --function foo

foo函数需要稍后在另一个库的util.py中使用:

def compile():
  compiler.compile(
    function=foo,
    etc
  )

通过 argparse 导入 foo 函数的最佳方式是什么?


一些初步的想法:

util.py:

def get_args():
  parser = argparse.ArgumentParser()
  parser.add_argument("--path", type=str)
  parser.add_argument("--function", type=str)
  return parser.parse_args()

def compile(path, function):
  import path 
  compiler.compile(
    function=path.function,
    etc
  )

if __name__ == "__main__":
  args = get_args()
  compile(
    path=args.path
    function=args.function
  )

但是通过 argparse 导入,并将其添加到函数中似乎效果不佳。

还有使用sys.path.append的想法:

def compile(path, function):
  import sys
  sys.path.append(path)

但是我不确定如何从中导入 foo 函数。

【问题讨论】:

    标签: python python-3.x argparse


    【解决方案1】:

    这个问题可以改写为“如何在给定路径的情况下导入 python 文件?”为此,我们可以使用https://stackoverflow.com/a/67692/5666087。这是一个代码示例,其中结合了该问题的答案和您的需求。

    import argparse
    import importlib.util
    import sys
    
    
    def get_function_object(path_to_pyfile: str, funcname: str):
        spec = importlib.util.spec_from_file_location("tmpmodulename", path_to_pyfile)
        module = importlib.util.module_from_spec(spec)
        sys.modules["tmpmodulename"] = module
        spec.loader.exec_module(module)
        if not hasattr(module, funcname):
            raise AttributeError(f"Cannot find function '{funcname}'in imported module")
        # TODO: Consider testing whether this object is a callable.
        return getattr(module, funcname)
    
    
    def get_args():
        parser = argparse.ArgumentParser()
        parser.add_argument("--path", type=str)
        parser.add_argument("--function", type=str)
        return parser.parse_args()
    
    
    if __name__ == "__main__":
        args = get_args()
        function = get_function_object(args.path, funcname=args.function)
        compiler.compile(function=funtion)
    

    【讨论】:

      猜你喜欢
      • 2018-05-02
      • 1970-01-01
      • 2017-10-22
      • 2021-09-09
      • 2021-12-20
      • 2018-06-21
      • 1970-01-01
      • 1970-01-01
      • 2022-11-17
      相关资源
      最近更新 更多